
proc positionWindow w {
    wm geometry $w +50+100
}
proc chk_relation {old_owner operator} {
	global info 
	set old_owner [string tolower [string trim $old_owner]]
	set operator [string tolower [string trim $operator]]
	log_info $info "old_owner: $old_owner; operator: $operator" 5
	if {$old_owner==$operator || $operator=="admin" || $old_owner=="{$operator}"} {
		return 1
	} else {
		return 0
	}
}

proc can_i_change {operator cur_env} {
	global info db_handle TREE_TB DB_NAME group_id user_id
	set operator [string tolower [string trim $operator]]
	set son_env [get_son_env $cur_env]
	set parent_env [get_parent_env $cur_env]
	if {$son_env=="0" && $parent_env=="0"} {
		log_info $info "create new root item" 2
		return "active"
	}
        log_info $info "son_env: $son_env; parent_env: $parent_env" 5
        set sql_qur "SELECT owner FROM $TREE_TB WHERE name='$son_env' and Parentid='$parent_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]

        set k 0

	log_info $info $sql_qur 2
        if {$infect_line >0} {
		if {$infect_line>1} {
	                log_info $info "Found $infect_line records in Tree for env: $cur_env! " 3
	                log_info $info "Should be only one, please tell admin to handle it. Currently we use the first one! " 3
		}
		#set owner [string tolower [string trim [::mysql::fetch $db_handle]]]
		set owner [string tolower [string trim [lindex $sql_ret_str 0]]]
		log_info $info "owner: $owner; operator: $operator" 5
		if {$owner==$operator || $operator=="admin" || $owner=="{$operator}"} {
			log_info $info "owner: $owner" 2
			return "active"
		} else {
			return "disabled"
		}
        } else {
                log_info $info "Fail to find env:cur_env record in DB tree !" 2
                return "disabled"
        }
}

proc log_info {info content severity} {
	global LOG_SEV run_case_no MAX_LOG_LINES
	
	append content "\n"
#	$info insert end "LOG_SEV: $LOG_SEV; current severity: $severity\n"
        $info tag configure sev(7) -foreground black 
        $info tag configure sev(6) -foreground green 
        $info tag configure sev(5) -foreground YellowGreen
        $info tag configure sev(4) -foreground yellow  -background grey
	$info tag configure sev(3) -foreground OrangeRed -background white
        $info tag configure sev(2) -foreground IndianRed
        $info tag configure sev(1) -foreground red
	if {$LOG_SEV >= $severity} {
		$info insert end "run_case_no:$run_case_no. $content" sev($severity)
                $info delete 1.0 "end - $MAX_LOG_LINES lines"
		$info see end
		#below puts line is for recording info in stdout file
		puts "run_case_no:$run_case_no. $content"
	}
}
proc close_db_and_exit {} {
	global db_handle info
#	if [catch {::mysql::close $db_handle} err_info] {
#		log_info $info "Fail to close DB, err_info: $err_info" 2
#		sleep 2
#		exit
#	} else {
#		log_info $info "close DB successfully!" 2
		log_info $info "quit...." 2
		exit
#	}
}
proc refresh_display {} {
	global DB_SERVER DB_USER DB_PASS DB_NAME TREE_TB db_handle info DB_PRV_SERVER DB_PRV_USER DB_PRV_PASS DB_PRV_NAME SW_DEV_CONN DB_KEEPALIVE
        # clear the tree / and recreate a new one
        bind .f.w <Destroy> "Tree:delitem .f.w /"
        Tree:newitem .f.w / -image idir

        display_database $DB_SERVER $DB_USER $DB_PASS $DB_NAME $TREE_TB $DB_PRV_SERVER $DB_PRV_USER $DB_PRV_PASS $DB_PRV_NAME $SW_DEV_CONN
}
proc display_database {DB_SERVER DB_USER DB_PASS DB_NAME TREE_TB DB_PRV_SERVER DB_PRV_USER DB_PRV_PASS DB_PRV_NAME SW_DEV_CONN} {
	global db_prv_handle db_handle info db_keepaliving DB_KEEPALIVE user_id group_id
        package require json

        set sql_qur "SELECT * FROM $TREE_TB where group_id='$group_id' ORDER BY Parentid, name"
        set sky_response [mysql_pack "$sql_qur" $DB_NAME ]
        set rows_num_pub [lindex $sky_response 0]
        set sql_ret_str_pub [lindex $sky_response 1]

        set sql_qur "SELECT * FROM $SW_DEV_CONN where user_id='$user_id' ORDER BY dev_name"
        set sky_prv_response [mysql_pack $sql_qur $DB_PRV_NAME ]
        set rows_num_prv [lindex $sky_prv_response 0]
        set sql_ret_str_prv [lindex $sky_prv_response 1]

        if {$rows_num_pub != -1} { 
		log_info $info "Connect to group database successfully!\n" 3
		log_info $info "Current TREE table has $rows_num_pub object!\n" 3
	} else {
		log_info $info "Failed to connect to group database!\n" 3
		log_info $info "Error Message: $sql_ret_str_pub" 3
        }
        if {$rows_num_prv != -1} { 
        	log_info $info "Connect to user database successfully!\n" 3
	        log_info $info "Current SW_DEV_CONN table has $rows_num_prv object!\n" 3	
        } else {
                log_info $info "Failed to connect to user database!\n" 3
                log_info $info "Error Message: $sql_ret_str_prv" 3
	}
	$info see end
	catch {unset row1}
	if {$rows_num_pub!= -1} {
        foreach cur_row $sql_ret_str_pub {
		set row1(1) [lindex $cur_row 0]
		set row1(2) [lindex $cur_row 1]
		set row1(3) [lindex $cur_row 2]
		set row1(4) [lindex $cur_row 3]
		set row1(5) [lindex $cur_row 4]
		set row1(6) [lindex $cur_row 5]
		set row1(7) [lindex $cur_row 6]
		log_info $info "row1(1) : $row1(1); row1(2) : $row1(2);row1(3) : $row1(3);row1(5):$row1(5)" 6
		if {$row1(3)!="0"} {
			set cur_env "/$row1(3)/$row1(2)"
		} else {
			set cur_env "/$row1(2)"
		}
		update_treeitem $cur_env $row1(4) $row1(5) $row1(6) $row1(7) 
	}
	}
	if {$DB_KEEPALIVE!=1} {
		set DB_KEEPALIVE 1
		db_keep_alive
	}
}
proc db_keep_alive {} {
	global info db_handle db_prv_handle DB_KEEPALIVE DB_KEEPALIVE_TIMER
	if $DB_KEEPALIVE {
#		set db_handle_state [::mysql::ping $db_handle]
#		set db_prv_handle_state [::mysql::ping $db_prv_handle]
		#log_info $info "db_handle state is $db_handle_state; db_prv_handle state is $db_prv_handle_state" 2
		#wait and then redo this proc
		set timer_ms [expr $DB_KEEPALIVE_TIMER*1000]
		after $timer_ms db_keep_alive
	}
	
}
proc update_treeitem {env desc state owner run_times} {
	global info DEFAULT_DESCRIPTION_OF_TREE
	log_info $info "env:$env; state:$state; owner:$owner; run_times:$run_times" 5
        set image_name ""
	set desc [string trim $desc]
	set state [string trim $state]
	log_info $info "state:$state; image_name:$image_name" 6
        if {$state==1} {
                if {$desc!="$DEFAULT_DESCRIPTION_OF_TREE" && $desc!=""} {
                        append image_name "ifile"
                } else {
                        append image_name "idir"
                }
        } else {
                append image_name "ipack"
        }
        if {$run_times=="0"} {append image_name "_disable"}
        log_info $info "env:$env; image_name:$image_name" 6
#	Tree:delitem .f.w $env
        Tree:newitem .f.w $env -image $image_name

}
proc chg_string_by_map_other {index map1_var dev_cfg} {
        global info
        upvar $map1_var map1
        set k 2
        while {[info exists map1($index,$k,1)]} {
                log_info $info "change: $map1($index,$k,1) change to $map1($index,$k,2)" 6
                set dev_cfg [string map "{$map1($index,$k,1)} {$map1($index,$k,2)}" $dev_cfg]
                log_info $info "update: $dev_cfg" 6
                incr k +1
        }
        return $dev_cfg
}
proc chg_string_by_map {map1_var dev_cfg} {
	global info
	upvar $map1_var map1 
	set k 2
        while {[info exists map1($k,1)]} {
                log_info $info "change: $map1($k,1) change to $map1($k,2)" 6
                set dev_cfg [string map "{$map1($k,1)} {$map1($k,2)}" $dev_cfg]
                log_info $info "update: $dev_cfg" 6
                incr k +1
        }
	return $dev_cfg
}
proc run_env {cur_env} {
	global array1 info ENV_DEV DEV_TB TREE_TB db_handle comm_array change_dut1 map1 interrupt map_other

	set i 1
	while { [info exists array1($i,1)] } {
	    if { $array1($i,2)==1 } {
		log_info $info "******************start to run command in device************************" 6
		log_info $info "array1($i,1): $array1($i,1)  array1($i,2): $array1($i,2) array1($i,3): $array1($i,3)" 6
		#get config from DB and set to variable dev_cfg 		
		set dev_cfg [string trim [get_cfg_of_dev_in_env $array1($i,3) $array1($i,1)]]
		log_info $info "dev_cfg:$dev_cfg" 5
		#check if cfg is NULL
		if {$dev_cfg!=""} {
			#####Add Checking for substitution 
			set env_dut1 ""
			set env_dut_new1 ""
			set env_options1 ""
			set env_options_new1 ""
			if {[string tolower [string range $array1($i,1) 0 8]]=="subst_dut"} {
				log_info $info "Handle substitute dut device" 3
				foreach map [split $dev_cfg "\n"] {
					if {[string index [string trim $map] 0]!="#"} {
						if {[regexp "(.*):(.*)" $map old_string map_name map_value]==1} {
							set name1 [string tolower [string trim $map_name]]
							set map_value [string tolower [string trim $map_value]]
							switch $name1 {
								env_dut { set env_dut1 $map_value}
								env_dut_new {set env_dut_new1 $map_value}
								env_options {set env_options1 $map_value}
								env_options_new {set env_options_new1 $map_value}
							}
                                                } elseif {[string trim $map]=="reset_mapping"} {
                                                        catch {unset map1}
						}
					}
				}	
				if {$env_dut1!="" && $env_dut_new1!=""} {
                                        log_info $info "env_dut1:$env_dut1; env_dut_new1:$env_dut_new1" 6
                                        log_info $info "env_options1:$env_options1; env_options_new1:$env_options_new1" 6
					if {[set_map $env_dut1 $env_dut_new1 $env_options1 $env_options_new1]!=0} {
						log_info $info "Map from $env_dut1 to $env_dut_new1 successfully" 3
						set change_dut1 1
						set_disable_chg_dut
						show_map 
					} else {
						log_info $info "Fail to map from $env_dut1 to $env_dut_new1" 2
					}  
				}
				incr i +1
				continue
			} elseif {[string tolower [string range $array1($i,1) 0 10]]=="subst_other"} {
				log_info $info "Handle substitute support devices" 3
				set change_num 0
				foreach map [split $dev_cfg "\n"] {
					if {[string index [string trim $map] 0]!="#"} {
						if {[regexp {(\d+)\s+(from|to)\s+(\S+)\s+(.*)} $map old_string index action name22 options22]==1} {
							if {$index > $change_num} {set change_num $index}
							log_info $info "index: $index; action:$action; name22: $name22; options22:$options22" 5
							set action [string tolower $action]
							set name2($index,$action) [string tolower [string trim $name22]]
							#set options2($index,$action) [string tolower [string trim $options22]]
							set options2($index,$action) [handle_string_special [string trim $options22]]
							#set options2($index,$action) [string trim $options22]
						} elseif {[string trim $map]=="reset_mapping"} {
							catch {unset map_other}
						}
					}
				}	
				set map_i 1
				for {set map_i 1} {$map_i<=$change_num} {incr map_i +1} { 
					if {[info exists name2($map_i,from)] && [info exists name2($map_i,to)] &&  \
					[info exists options2($map_i,from)] && [info exists options2($map_i,to)]} {
          					if {[set index_in_map_other [set_map_other 0 $name2($map_i,from) $name2($map_i,to) \
						$options2($map_i,from) $options2($map_i,to)]]!=0} {
          						log_info $info "Map from $name2($map_i,from) to $name2($map_i,to) successfully" 3
          						set change_dut1 1
          						set_disable_chg_dut
          						show_map_other $index_in_map_other
          					} else {
          						log_info $info "Fail to map from $name2($map_i,from) to $name2($map_i,to)" 2
          					}  
					} else {
						log_info $info "substitute item $map_i doesnot have enough info, ignore it" 2
					}	
				}
				incr i +1
				continue				
			} else {
				log_info $info "Handle standard devices" 4
			}
			#####Finish Checking for substitution
			#####Sep 28,2006, move below code to run_comm_on_dev which can be used for config and test
#			#check if we need to change DUT
#			set array1($i,1) [string tolower [string trim $array1($i,1)]]
#			if {$array1($i,1) == $map1(1,1) && $change_dut1==1} {
#				###in case override previous mapping, mapping device only when device name changed
#				###Case: 1st mapping: DUT1(test_p2)->FG400(p2_v2), 2nd mapping: DUT1(phase1)->DUT1(phase1-interface)
#				if {$map1(1,1)!=$map1(1,2)} {set host $map1(1,2)}
#				if {![info exists host]} {set host $map1(1,1)}
#				set dev_cfg [chg_string_by_map map1 $dev_cfg]
#			} else {
#				set host $array1($i,1)
#			}
#			#check if we need to change Test_support devices
#			set ii 1
#			while {[info exists map_other($ii,1,1)] && $change_dut1==1} {
#				log_info $info "array1($i,1): $array1($i,1); map_other($ii,1,1): $map_other($ii,1,1)  -> $map_other($ii,1,2)" 2
#				if {[string trim $array1($i,1)] == [string trim $map_other($ii,1,1)]} {
#	                                ###in case override previous mapping, mapping device only when device name changed
#	                                ###Case: 1st mapping: DUT1(test_p2)->FG400(p2_v2), 2nd mapping: DUT1(phase1)->DUT1(phase1-interface)
#        	                        if {$map_other($ii,1,1)!=$map_other($ii,1,2)} {set host $map_other($ii,1,2)}
#                	                if {![info exists host]} {set host $map_other($ii,1,1)}
#					set dev_cfg [chg_string_by_map_other $ii map_other $dev_cfg]
#					log_info $info "change config for $array1($i,1)" 2
#				}
#				incr ii +1
#			}
			set host $array1($i,1)
			#run dev_cfg in dev
			set line1_dev_cfg [lindex [split $dev_cfg "\n"] 0]
			if {[string range $line1_dev_cfg 0 18]=="exec restore config"} {
				set dev_cfg [trimfirst $dev_cfg $line1_dev_cfg]
				if {[run_comm_on_dev $host $line1_dev_cfg 1]==0} {
               	                	log_info $info "run restore config on $host failed" 2;
                               	} else {
					log_info $info "system is restoring image, system will sleep for 120 seconds, wait for system reboot." 3
					sleep 120
				}
			}
			set dev_cfg [trimfirst $dev_cfg "\n"]
			ch_string_to_array $dev_cfg
			if {[run_comm_on_dev $host $dev_cfg 1]!=0} {
       	                	log_info $info "Configure $host successfully!" 2
                       	} else {
				log_info $info "Fail to configure $host!" 1
			}
		} else {
			log_info $info "dev_cfg for $array1($i,1) is NULL, ignore it" 2
		}
	     } else {
		     log_info $info "disable running $array1($i,3) in env $array1($i,1)" 4
	     }
	     incr i +1
	}
}
proc get_belong {parentID} {
	global db_handle info TREE_TB
	set sql_qur "SELECT * FROM $TREE_TB WHERE name='$parentID' and group_id='$group_id'"
        set sky_response [mysql_pack "$sql_qur" $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

	if {$parent_line =="1"} {
		$info insert end "Found parent line : $parentID!\n"
		$info see end
		set cur_row [lindex $sql_ret_str 0]
		set row1(1) [lindex $cur_row 0]
		set row1(2) [lindex $cur_row 1]
		set row1(3) [lindex $cur_row 2]	
		return $row1(3)
	} else {
		$info insert end "Found too many parent line : $parentID!\n"
		$info see end
		return 0
	}
}
proc input_env_to_db {} {
	global DB_NAME row1 info operator DEFAULT_DESCRIPTION_OF_TREE group_id
	if {$row1(2)==""} {set row1(2) "0"}
	set belongto $row1(2)
	set row1(1) [string trim $row1(1)]
	set sql_qur "INSERT INTO tree (id,name,parentid,des,state,owner,run_times,group_id) values ('','$row1(1)','$belongto','$DEFAULT_DESCRIPTION_OF_TREE','1','$operator','1','$group_id')"
        set sky_response [mysql_pack "$sql_qur" $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]

	if {$infect_line =="1"} {
		log_info $info "Insert $row1(1) Into env database successfully!" 3
		log_info $info "belongto: $belongto; row1(1): $row1(1)" 6
		return 1
	} else {
		log_info $info "Fail to insert $row1(1) into env database !" 2
		log_info $info "$infect_line" 3
		return 0
	}
}
proc update_env_test_desc_in_db {desc state order cur_test_name cur_env} {
        global DB_NAME info ENV_TEST
        set new_content [$desc get 1.0 end]
        set new_state [string trim [$state get]]
        set new_order [string trim [$order get]]

	#        set new_content [string map {\" \\" \' \\' \\\\ \\\\\\\\} $new_content]
	set new_content [handle_string_special $new_content]
        set sql_qur "UPDATE $ENV_TEST SET description='$new_content',state='$new_state',`order`='$new_order' WHERE test_name='$cur_test_name' and env_name='$cur_env'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]


        log_info $info $sql_qur 2
        if {$infect_line  =="1"} {
                log_info $info "Update test record for $cur_test_name in $cur_env successfully!" 3
                return 1
        } else {
                log_info $info "Fail to find env record in DB tree !" 2
                return 0
        }
}

proc update_desc_in_db {desc owner state run_times cur_env} {
	global DB_NAME info
        set son_env [get_son_env $cur_env]
        set parent_env [get_parent_env $cur_env]
	set new_content [string trim [$desc get 1.0 end]]
	set new_owner [string trim [$owner get]]
	set new_state [string trim [$state get]]
	set new_run_times [string trim [$run_times get]]
        #set new_content [string map {\" \\" \' \\' \\\\ \\\\\\\\} $new_content]
        set new_content [handle_string_special $new_content]
        set sql_qur "UPDATE tree SET des='$new_content',state='$new_state',owner='$new_owner',run_times='$new_run_times' WHERE name='$son_env' and Parentid='$parent_env'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]


        log_info $info $sql_qur 2
        if {$infect_line  =="1"} {
                log_info $info "Update record for $son_env in $parent_env successfully!" 3
		#update_treeitem "/$cur_env" $new_content $new_state $new_owner $new_run_times
		Tree:delitem .f.w "/$cur_env"
		refresh_display
                return 1
        } else {
                log_info $info "Fail to find env record in DB tree !" 2
                return 0
        }
}
proc display_desc {desc state owner run_times cur_env} {
	global info operator
	set can_change [can_i_change $operator $cur_env]
	set son_env [get_son_env $cur_env]
	set parent_env [get_parent_env $cur_env]
	append desc "
last edit:"
	append desc [clock format [clock second] -format "%b %d %H:%M %Y"]
	append desc " by $operator"
#	 tk_messageBox -icon info -type ok -title "About Env_Setup" -message $desc	
        set top1 .desc$parent_env$son_env 
        catch {destroy $top1}
        toplevel $top1
        wm title $top1 "Edit $son_env in $parent_env"
        wm iconname $top1 "iconname?"
        positionWindow $top1
	
        set w [frame $top1.up]
        set d [frame $top1.desc]
        set command [frame $top1.cmd]
	pack $w $d $command -side top -expand yes -fill both
	frame $w.left
        frame $w.right
        pack $w.left -side left -expand no -padx 1 -pady 10 -fill both 
        pack $w.right -side left -expand yes -padx 10 -pady 10 -fill both
        label $w.left.owner -text "Owner:" -padx 0 -pady 1 -width 15 -anchor e
        label $w.left.state -text "State:" -padx 0 -pady 1 -width 15 -anchor e
        label $w.left.run_times -text "Run_times:" -padx 0 -pady 1 -width 15 -anchor e

        set widget_owner [entry $w.right.owner -width 45 -relief sunken] 
        set widget_state [entry $w.right.state -width 3 -relief sunken ]
        set widget_run_times [entry $w.right.run_times -width 5 -relief sunken ]
	pack $w.left.owner $w.left.state $w.left.run_times -side top 
	pack $w.right.owner $w.right.state $w.right.run_times -side top -fill both 

        label $d.desc -text "Description:" -padx 10 -pady 1 -width 14 -anchor e
        set desc_txt [text $d.txt -yscrollcommand "$d.sb set"]
        scrollbar $d.sb -orient vertical -command "$desc_txt yview"
	pack $d.desc -side left -fill both
	pack $desc_txt -side left -expand 1 -fill both
        pack $d.sb -side right -fill both
        $desc_txt insert end $desc
        $widget_owner insert end $owner
        $widget_state insert end $state
        $widget_run_times insert end $run_times
#        button $command.confirm -text Confirm -state $can_change -command "update_desc_in_db $desc_txt $widget_owner $widget_state $widget_run_times $cur_env; catch {destroy $top1} "
        button $command.confirm -text Confirm -command " 
		update_desc_in_db $desc_txt $widget_owner $widget_state $widget_run_times $cur_env; 
		catch {destroy $top1} "
        button $command.cancel -text Cancel -command " catch {destroy $top1} ; return 0 "
        pack $command.confirm $command.cancel -side left -expand 1

}
proc display_desc_test {desc state order cur_test_name cur_env can_change} {
        global info
        set top1 .desc$cur_test_name
        catch {destroy $top1}
        toplevel $top1
        wm title $top1 "Edit $cur_test_name in $cur_env"
        wm iconname $top1 "iconname?"
        positionWindow $top1

        set w [frame $top1.up]
        set d [frame $top1.desc]
        set command [frame $top1.cmd]
        pack $w $d $command -side top -expand yes -fill both
        frame $w.left
        frame $w.right
        pack $w.left -side left -expand no -padx 1 -pady 10 -fill both
        pack $w.right -side left -expand yes -padx 10 -pady 10 -fill both
        label $w.left.state -text "State:" -padx 0 -pady 1 -width 15 -anchor e
        label $w.left.order -text "Order" -padx 0 -pady 1 -width 15 -anchor e

        set widget_state [entry $w.right.state -width 3 -relief sunken ]
        set widget_order [entry $w.right.order -width 5 -relief sunken ]
        pack $w.left.state $w.left.order -side top
        pack $w.right.state $w.right.order -side top -fill both

        label $d.desc -text "Description:" -padx 10 -pady 1 -width 14 -anchor e
        set desc_txt [text $d.txt -yscrollcommand "$d.sb set"]
        scrollbar $d.sb -orient vertical -command "$desc_txt yview"
        pack $d.desc -side left -fill both
        pack $desc_txt -side left -expand 1 -fill both
        pack $d.sb -side right -fill both
        $desc_txt insert end $desc
        $widget_state insert end $state
        $widget_order insert end $order
        button $command.confirm -text Confirm -command "update_env_test_desc_in_db $desc_txt $widget_state $widget_order $cur_test_name $cur_env; catch {destroy $top1} "
        #button $command.confirm -text Confirm -state $can_change -command "update_env_test_desc_in_db $desc_txt $widget_state $widget_order $cur_test_name $cur_env; catch {destroy $top1} "
        button $command.cancel -text Cancel -command " catch {destroy $top1} ; return 0 "
        pack $command.confirm $command.cancel -side left -expand 1

}

proc edit_test_env {cur_widget can_change} {
        global DB_NAME cur_env info ENV_TEST array_test group_id
        regexp \.f\.out_window\.oper\.test_sw\.f\.frame\.(\[0-9]*) $cur_widget unuse no
	set cur_test_name $array_test($no,1)

        set son_env [get_son_env $cur_env]
        set parent_env [get_parent_env $cur_env]
        log_info $info "son_env: $son_env; parent_env: $parent_env" 5
        set sql_qur "SELECT description,state,`order` FROM $ENV_TEST WHERE env_name='$cur_env' and test_name='$cur_test_name' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]


        log_info $info $sql_qur 2
        if {$infect_line  >0} {
                log_info $info "Found record in DB for test:$cur_test_name in env: $cur_env!" 3
                set get_value [lindex $sql_ret_str 0]
                #set get_value [::mysql::fetch $db_handle]
#               set env_desc [string range [::mysql::fetch $db_handle] 1 end-1]
                set test_desc [string range [lindex $get_value 0] 0 end]
                set test_state [lindex $get_value 1]
                set test_order [lindex $get_value 2]
                display_desc_test $test_desc $test_state $test_order $cur_test_name $cur_env $can_change
                return 1
        } else {
                log_info $info "Fail to find env record in DB tree !" 2
                return 0
        }
}
proc get_son_env {cur_env} {
	return [lindex [split $cur_env "/"] end]
}
proc get_parent_env {cur_env} {
        global info
	set son_env [get_son_env $cur_env]
        set parent_env [trimend $cur_env "$son_env"]
        if {[string trim $parent_env]!=""} { 
		set parent_env [trimend $parent_env "/"] 
	} else {
		set parent_env "0"
	}
        log_info $info "cur_env: $cur_env; son_env: $son_env; parent_env: $parent_env " 4
	return $parent_env
}
proc edit_env_des {cur_env} {
	global DB_NAME info TREE_TB group_id
	set son_env [get_son_env $cur_env]
	set parent_env [get_parent_env $cur_env]
        log_info $info "son_env: $son_env; parent_env: $parent_env" 5
        set sql_qur "SELECT des,state,owner,run_times FROM $TREE_TB WHERE name='$son_env' and Parentid='$parent_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]


	log_info $info $sql_qur 2
        if {$infect_line  >0} {
                log_info $info "Found record in DB for env: $cur_env!" 3
                set get_value [lindex $sql_ret_str 0]
#		set env_desc [string range [::mysql::fetch $db_handle] 1 end-1]	
                set env_desc [string range [lindex $get_value 0] 0 end]
                set env_state [lindex $get_value 1]
                set env_owner [lindex $get_value 2]
                set env_run_times [lindex $get_value 3]

		display_desc $env_desc $env_state $env_owner $env_run_times $cur_env
		return 1
        } else {
                log_info $info "Fail to find env record in DB tree !" 2
                return 0
        }
}
proc help_chg_name_env {parent_env son_env new_parent_env new_value_widget add_newitem} {
	set new_value [string trim [$new_value_widget get]]
	confirm_chg_name_env $parent_env $son_env $new_parent_env $new_value $add_newitem
}

proc confirm_chg_name_env {parent_env son_env new_parent_env new_value add_newitem} {
	global commit_chg_env_name DB_NAME info ENV_DEV ENV_DUT ENV_TEST TREE_TB operator
	if {$parent_env=="0"} {
		set global_old_env "$son_env" 
	} else {
		set global_old_env "$parent_env/$son_env" 
	}
	if {$new_parent_env=="0"} {
		set global_new_env "$new_value" 
	} else {
		set global_new_env "$new_parent_env/$new_value" 
	}
	if {$global_old_env==$global_new_env} {
		log_info $info "global_old_env: $global_old_env; global_new_env: $global_new_env; add_newitem: $add_newitem" 2
		log_info $info "old and new env are the same, don't need change" 2
		return 1
	} else {
		log_info $info "global_old_env: $global_old_env; global_new_env: $global_new_env; add_newitem: $add_newitem" 2
	}

	set sql_qur "SELECT des,state FROM $TREE_TB WHERE name='$son_env' and Parentid='$parent_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]


	set new_des ""
	set new_state "1"
        if {$infect_line !="0"} {
		set value_string [lindex $sql_ret_str 0]
               	set new_des [handle_string_special [lindex $value_string 0]]
                set new_state [lindex $value_string 1]
        } 
	
	set sql_qur "SELECT * FROM $TREE_TB WHERE name='$new_value' and Parentid='$new_parent_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]


        if {$infect_line !="0"} {
                log_info $info "The new name is already existed! $infect_line . Combine them" 3
        } 
#Change name in $TREE_TB table
	if {$add_newitem==0} {
		set sql_qur "UPDATE $TREE_TB set name='$new_value',Parentid='$new_parent_env',des='$new_des',state='$new_state' \
		WHERE name='$son_env' and Parentid='$parent_env'"
	} else {
		set sql_qur "INSERT into `$TREE_TB` (`id`,`name`,`parentid`,`des`,`state`,`owner`,`group_id`) values ('', '$new_value', \ 
		 '$new_parent_env','$new_des','$new_state','$operator','$group_id')"
	}
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]


        if {$infect_line =="1"} {
                log_info $info "Change name in $TREE_TB table successfully! $infect_line" 3
		if {$add_newitem==0} {	Tree:delitem .f.w /$global_old_env}		
		Tree:newitem .f.w /$global_new_env -image idir
        } else {
                log_info $info "Change name in $TREE_TB table failed !" 2
        }

	catch {unset chg}
	set sql_qur "SELECT id,name,Parentid,des,state,run_times,owner FROM $TREE_TB WHERE Parentid='$global_old_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]

        set k 0

        if {$infect_line !="0"} {
                log_info $info "Change parentID in $TREE_TB table! $infect_line" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
			set value_string [lindex $sql_ret_str $k]
                        incr k +1
			#set value_string [::mysql::fetch $db_handle]
        	        set chg($i,1) [lindex $value_string 0]
                	set chg($i,2) [lindex $value_string 1]
                	set chg($i,3) [lindex $value_string 2]
                	set chg($i,4) [handle_string_special [lindex $value_string 3]]
                	set chg($i,5) [lindex $value_string 4]
			set chg($i,6) [string map "$global_old_env $global_new_env" $chg($i,3)] 
                	set chg($i,7) [lindex $value_string 5]
                	set chg($i,8) [lindex $value_string 6]
		}
		for  {set i 1} {$i<=$infect_line} {incr i +1} {
			if {$add_newitem==0} {
				set sql_qur "UPDATE $TREE_TB set Parentid='$chg($i,6)' where id='$chg($i,1)' "
			} else {
				set sql_qur "INSERT into `$TREE_TB` (`id`,`name`,`parentid`,`des`,`state`,`run_times`,`owner`,`group_id` ) values ('','$chg($i,2)','$chg($i,6)',\"$chg($i,4)\",'$chg($i,5)','$chg($i,7)','$chg($i,8)','$group_id')"
			}
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line1 [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]

		        if {$infect_line1 =="1"} {
		                log_info $info "Change name in $TREE_TB table successfully! $chg($i,2)" 3
				catch {Tree:newitem .f.w /$chg($i,6)/$chg($i,2) -image idir}
		        } else {
                		log_info $info "Change name in $TREE_TB table failed ! $chg($i,2)" 2
		        }
		}
        } else {
                log_info $info "No parentid in $TREE_TB table need be changed !" 2
        }

	catch {unset chg}
	set sql_qur "SELECT id,name,Parentid,des,state,run_times,owner FROM $TREE_TB WHERE Parentid like '$global_old_env/%' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]

        set k 0

        if {$infect_line !="0"} {
                log_info $info "Change parentID in $TREE_TB table! $infect_line" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
			set value_string [lindex $sql_ret_str $k]
                        incr k +1
			#set value_string [::mysql::fetch $db_handle]
        	        set chg($i,1) [lindex $value_string 0]
                	set chg($i,2) [lindex $value_string 1]
                	set chg($i,3) [lindex $value_string 2]
                	set chg($i,4) [handle_string_special [lindex $value_string 3]]
                	set chg($i,5) [lindex $value_string 4]
			set chg($i,6) [string map "$global_old_env/ $global_new_env/" $chg($i,3)] 
                        set chg($i,7) [lindex $value_string 5]
                        set chg($i,8) [lindex $value_string 6]

		}
		for  {set i 1} {$i<=$infect_line} {incr i +1} {
			if {$add_newitem==0} {
				set sql_qur "UPDATE $TREE_TB set Parentid='$chg($i,6)' where id='$chg($i,1)'"
			} else {
				set sql_qur "INSERT into `$TREE_TB` (`id`,`name`,`parentid`,`des`,`state`,`run_times`,`owner`,`group_id`) values ('','$chg($i,2)','$chg($i,6)',\"$chg($i,4)\",'$chg($i,5)','$chg($i,7)','$chg($i,8)','$group_id')"
			}
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line1 [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]


		        if {$infect_line1 =="1"} {
		                log_info $info "Change name in $TREE_TB table successfully! $chg($i,2)" 3
				catch {Tree:newitem .f.w /$chg($i,6)/$chg($i,2) -image idir}
		        } else {
                		log_info $info "Change name in $TREE_TB table failed ! $chg($i,2)" 2
		        }
		}
        } else {
                log_info $info "No parentid in $TREE_TB table need be changed !" 2
        }
	
#Change name in  ENV_DEV table	
	catch {unset chg}
        set sql_qur "SELECT id,env_name,sub_env,dev,flag,cfg,`order` FROM $ENV_DEV WHERE env_name='$global_old_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]

        set k 0

        if {$infect_line !="0"} {
                log_info $info "Change env_name in $ENV_DEV table! $infect_line" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
			set value_string [lindex $sql_ret_str $k]
                        incr k +1
        	        set chg($i,1) [lindex $value_string 0]
                	set chg($i,2) [lindex $value_string 1]
                	set chg($i,3) [lindex $value_string 2]
                	set chg($i,4) [lindex $value_string 3]
                	set chg($i,5) [handle_string_special  [lindex $value_string 4]]
                	set chg($i,6) [handle_string_special  [lindex $value_string 5]]
			set chg($i,7) [string map "$global_old_env $global_new_env" $chg($i,2)] 
                	set chg($i,8) [lindex $value_string 6]
		}
		for  {set i 1} {$i<=$infect_line} {incr i +1} {
			if {$add_newitem==0} {
				set sql_qur "UPDATE $ENV_DEV set env_name='$chg($i,7)' where id='$chg($i,1)'"
			} else {
				set sql_qur "INSERT INTO `$ENV_DEV` (`id`,`env_name`,`sub_env`,`dev`,`flag`,`cfg`,`order`,`group_id`) values ('','$chg($i,7)','$chg($i,3)','$chg($i,4)',\"$chg($i,5)\",\"$chg($i,6)\",'$chg($i,8)','$group_id')"
			}
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line1 [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]

		        if {$infect_line1 =="1"} {
		                log_info $info "Change env_name in $ENV_DEV table successfully! $chg($i,4)" 3
		        } else {
                		log_info $info "Change env_name in $ENV_DEV table failed ! $chg($i,4)" 2
		        }
		}
        } else {
                log_info $info "No other env_name in $ENV_DEV table need be changed !" 2
        }
	
	catch {unset chg}
	set sql_qur "SELECT id,env_name,sub_env,dev,flag,cfg,`order` FROM $ENV_DEV WHERE env_name like '$global_old_env/%' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0
        if {$infect_line !="0"} {
                log_info $info "Change env_name in $ENV_DEV table! $infect_line" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
			set value_string [lindex $sql_ret_str $k]
                        incr k +1
			#set value_string [::mysql::fetch $db_handle]
        	        set chg($i,1) [lindex $value_string 0]
                	set chg($i,2) [lindex $value_string 1]
                	set chg($i,3) [lindex $value_string 2]
                	set chg($i,4) [lindex $value_string 3]
                	set chg($i,5) [handle_string_special [lindex $value_string 4]]
                	set chg($i,6) [handle_string_special [lindex $value_string 5]]
			set chg($i,7) [string map "$global_old_env/ $global_new_env/" $chg($i,2)] 
                	set chg($i,8) [lindex $value_string 6]
		}
		for  {set i 1} {$i<=$infect_line} {incr i +1} {
			if {$add_newitem==0} {
				set sql_qur "UPDATE $ENV_DEV set env_name='$chg($i,7)' where id='$chg($i,1)'"
			} else {
				set sql_qur "INSERT INTO `$ENV_DEV` (`id`,`env_name`,`sub_env`,`dev`,`flag`,`cfg`,`order`,`group_id`) values ('','$chg($i,7)','$chg($i,3)','$chg($i,4)',\"$chg($i,5)\",\"$chg($i,6)\",'$chg($i,8)','$group_id')"
			}
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line1 [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]

		        if {$infect_line1 =="1"} {
		                log_info $info "Change env_name in $ENV_DEV table successfully! $chg($i,4)" 3
		        } else {
                		log_info $info "Change env_name in $ENV_DEV table failed ! $chg($i,4)" 2
		        }
		}
        } else {
                log_info $info "No other env_name in $ENV_DEV table need be changed !" 2
        }
#Change name in  ENV_DUT table	
	catch {unset chg}
	set sql_qur "SELECT id,env_name,dut_name,options,dut_changeto,options_changeto FROM $ENV_DUT WHERE env_name='$global_old_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0
        if {$infect_line !="0"} {
                log_info $info "Change env_name in $ENV_DUT table! $infect_line" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
			set value_string [lindex $sql_ret_str $k]
                        incr k +1
			#set value_string [::mysql::fetch $db_handle]
        	        set chg($i,1) [lindex $value_string 0]
                	set chg($i,2) [lindex $value_string 1]
                	set chg($i,3) [lindex $value_string 2]
                	set chg($i,4) [lindex $value_string 3]
                	set chg($i,5) [lindex $value_string 4]
                	set chg($i,6) [lindex $value_string 5]
			set chg($i,7) [string map "$global_old_env $global_new_env" $chg($i,2)] 
		}
		for  {set i 1} {$i<=$infect_line} {incr i +1} {
			if {$add_newitem==0} {
				set sql_qur "UPDATE $ENV_DUT set env_name='$chg($i,7)' where id='$chg($i,1)'"
			} else {
				set sql_qur "INSERT INTO `$ENV_DUT` (`id`,`env_name`,`dut_name`,`options`,`dut_changeto`,`options_changeto`,`group_id`) values ('','$chg($i,7)','$chg($i,3)','$chg($i,4)','$chg($i,5)','$chg($i,6)','$group_id')"
			}
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line1 [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]
                        set k 0

		        if {$infect_line1 =="1"} {
		                log_info $info "Change/Add name in $ENV_DUT table successfully! $chg($i,7)" 3
		        } else {
                		log_info $info "Change/Add name in $ENV_DUT table failed ! $chg($i,7)" 2
		        }
		}
        } else {
                log_info $info "No other env_name in $ENV_DUT table need be changed !" 2
        }

	catch {unset chg}
	set sql_qur "SELECT id,env_name,dut_name,options,dut_changeto,options_changeto FROM $ENV_DUT WHERE env_name like '$global_old_env/%' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line !="0"} {
                log_info $info "Change env_name in $ENV_DUT table! $infect_line" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
			set value_string [lindex $sql_ret_str $k]
                        incr k +1
			#set value_string [::mysql::fetch $db_handle]
        	        set chg($i,1) [lindex $value_string 0]
                	set chg($i,2) [lindex $value_string 1]
                	set chg($i,3) [lindex $value_string 2]
                	set chg($i,4) [lindex $value_string 3]
                	set chg($i,5) [lindex $value_string 4]
                	set chg($i,6) [lindex $value_string 5]
			set chg($i,7) [string map "$global_old_env/ $global_new_env/" $chg($i,2)] 
		}
		for  {set i 1} {$i<=$infect_line} {incr i +1} {
			if {$add_newitem==0} {
				set sql_qur "UPDATE $ENV_DUT set env_name='$chg($i,7)' where id='$chg($i,1)'"
			} else {
				set sql_qur "INSERT INTO `$ENV_DUT` (`id`,`env_name`,`dut_name`,`options`,`dut_changeto`,`options_changeto`,`group_id`) values ('','$chg($i,7)','$chg($i,3)','$chg($i,4)','$chg($i,5)','$chg($i,6)','$group_id')"
			}
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line1 [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]
                        set k 0

		        if {$infect_line1 =="1"} {
		                log_info $info "Change/Add name in $ENV_DUT table successfully! $chg($i,7)" 3
		        } else {
                		log_info $info "Change/Add name in $ENV_DUT table failed ! $chg($i,7)" 2
		        }
		}
        } else {
                log_info $info "No other env_name in $ENV_DUT table need be changed !" 2
        }
	
#Change name in  ENV_TEST table	
	catch {unset chg}
	set sql_qur "SELECT id,env_name,test_name,test_group,exp_result,description,state,`order` FROM $ENV_TEST WHERE env_name='$global_old_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line !="0"} {
                log_info $info "Change env_name in $ENV_TEST table! $infect_line" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
			set value_string [lindex $sql_ret_str $k]
                        incr k +1
			#set value_string [::mysql::fetch $db_handle]
        	        set chg($i,1) [lindex $value_string 0]
                	set chg($i,2) [lindex $value_string 1]
                	set chg($i,3) [lindex $value_string 2]
                	set chg($i,4) [lindex $value_string 3]
                	set chg($i,5) [handle_string_special  [lindex $value_string 4]]
                	set chg($i,6) [handle_string_special  [lindex $value_string 5]]
                	set chg($i,7) [lindex $value_string 6]
			set chg($i,8) [string map "$global_old_env $global_new_env" $chg($i,2)] 
                	set chg($i,9) [lindex $value_string 7]
		}
		for  {set i 1} {$i<=$infect_line} {incr i +1} {
			if {$add_newitem==0} {
				set sql_qur "UPDATE $ENV_TEST set env_name='$chg($i,8)' where id='$chg($i,1)'"
			} else {
				set sql_qur "INSERT INTO `$ENV_TEST` (`id`,`env_name`,`test_name`,`test_group`,`exp_result`,`description`,`state`,`order`,`group_id`) values ('','$chg($i,8)','$chg($i,3)','$chg($i,4)',\"$chg($i,5)\",\"$chg($i,6)\",'$chg($i,7)','$chg($i,9)','$group_id')"
			}
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line1 [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]

		        if {$infect_line1 =="1"} {
		                log_info $info "Change name in $ENV_TEST table successfully! $chg($i,3)" 3
		        } else {
                		log_info $info "Change name in $ENV_TEST table failed ! $chg($i,3)" 2
		        }
		}
        } else {
                log_info $info "No other env_name in $ENV_TEST table need be changed !" 2
        }
	
	catch {unset chg}
	set sql_qur "SELECT id,env_name,test_name,test_group,exp_result,description,state,`order` FROM $ENV_TEST WHERE env_name like '$global_old_env/%' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line !="0"} {
                log_info $info "Change env_name in $ENV_TEST table! $infect_line" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
			set value_string [lindex $sql_ret_str $k]
                        incr k +1
        	        set chg($i,1) [lindex $value_string 0]
                	set chg($i,2) [lindex $value_string 1]
                	set chg($i,3) [lindex $value_string 2]
                	set chg($i,4) [lindex $value_string 3]
                	set chg($i,5) [handle_string_special [lindex $value_string 4]]
                	set chg($i,6) [handle_string_special [lindex $value_string 5]]
                	set chg($i,7) [lindex $value_string 6]
			set chg($i,8) [string map "$global_old_env/ $global_new_env/" $chg($i,2)] 
                	set chg($i,9) [lindex $value_string 7]
		}
		for  {set i 1} {$i<=$infect_line} {incr i +1} {
			if {$add_newitem==0} {
				set sql_qur "UPDATE $ENV_TEST set env_name='$chg($i,8)' where id='$chg($i,1)'"
			} else {
				set sql_qur "INSERT INTO `$ENV_TEST` (`id`,`env_name`,`test_name`,`test_group`,`exp_result`,`description`,`state`,`order`,`group_id`) values ('','$chg($i,8)','$chg($i,3)','$chg($i,4)',\"$chg($i,5)\",\"$chg($i,6)\",'$chg($i,7)','$chg($i,9)','$group_id')"
			}
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line1 [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]
                        set k 0

		        if {$infect_line1 =="1"} {
		                log_info $info "Change name in $ENV_TEST table successfully! $chg($i,3)" 3
		        } else {
                		log_info $info "Change name in $ENV_TEST table failed ! $chg($i,3)" 2
		        }
		}
        } else {
                log_info $info "No other env_name in $ENV_TEST table need be changed !" 2
        }
	set commit_chg_env_name 1
}	
proc upgrade_table {} {
        #this proc is useless, need remove it
	global info DB_NAME
	for {set id_value 1} {$id_value<=1002} {incr id_value +1} {	
        set sql_qur "SELECT * from test where id='$id_value' order by `test_name`"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set test_num [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$test_num >"0"} {
        	log_info $info "Good, Found $test_num test records in table test!" 4
		for {set cur_id 1} {$cur_id <=$test_num} {incr cur_id +1} {
	                set cur_row [lindex $sql_ret_str $k]
                        incr k +1
                        set test_name [lindex $cur_row 1]
                        set env_name [lindex $cur_row 2]
#                        set test_desc [string map {\" \\" \' \\' \( \\\( \) \\\)} [lindex $cur_row 3]]
                        set test_desc [handle_string_special [lindex $cur_row 3]]
                        set test_type [lindex $cur_row 4]
                        set test_cmd [string map {\" \\" \' \\' \( \\\( \) \\\)} [string trim [lindex $cur_row 5]]]
                        set test_src [lindex $cur_row 6]
                        set test_dst [lindex $cur_row 7]
                        set test_exp_resu [string trim [string map {\" \\" \' \\' \( \\\( \) \\\)} [lindex $cur_row 8]]]
                        set test_pre_src [string trim [lindex $cur_row 9]]
                        set test_pre_cmd [string map {\" \\" \' \\' \( \\\( \) \\\)} [string trim [lindex $cur_row 10]]]
                        set test_post_src [string trim [lindex $cur_row 11]]
                        set test_post_cmd [string map {\" \\" \' \\' \( \\\( \) \\\)} [string trim [lindex $cur_row 12]]]
                        set test_sleep [lindex $cur_row 13]
                        set test_round_times [lindex $cur_row 14]
                        set test_belong_group [lindex $cur_row 15]
                        set test_state [lindex $cur_row 16]
                        set test_exit_after_pre_cmd [lindex $cur_row 17]
                        set test_exit_after_cmd [lindex $cur_row 18]
                        set test_negate_pre_cmd [lindex $cur_row 19]
                        set test_negate_cmd [lindex $cur_row 20]
                        set test_negate_post_cmd [lindex $cur_row 21]
                        set test_new_connection [lindex $cur_row 22]
                        set test_owner [lindex $cur_row 23]

                        set test_name_new $test_name
                        set test_desc_new $test_desc
                        set test_type_new $test_type 
#			if {[string trim $test_pre_src]!=""]} {
	                        set test_cmd_new(1) $test_pre_cmd
	                        set test_dev_new(1) $test_pre_src
	                        set test_negate(1) $test_negate_pre_cmd
	                        set test_sleep_new(1) $test_sleep
	                        set test_exit_after_cmd_new(1) $test_exit_after_pre_cmd
				set test_order_new(1) 1
				set test_new_conn_new(1) 1
				set test_prev_conn_new(1) 0
				set test_in_round_new(1) 1
				set test_stop_test_new(1) 1
#			}
#                        if {[string trim $test_src]!=""]} {
                                set test_cmd_new(2) $test_cmd
				if {$test_exp_resu!=""} {append test_cmd_new(2) "|||$test_exp_resu"}
                                set test_dev_new(2) $test_src
                                set test_negate(2) $test_negate_cmd
                                set test_sleep_new(2) 0
                                set test_exit_after_cmd_new(2) 1
                                set test_order_new(2) 2
                                set test_new_conn_new(2) 1
                                set test_prev_conn_new(2) 0
                                set test_in_round_new(2) 1
                                set test_stop_test_new(2) 1
#                        }
#                        if {[string trim $test_post_src]!=""]} {
                                set test_cmd_new(3) $test_post_cmd
                                set test_dev_new(3) $test_post_src
                                set test_negate(3) $test_negate_post_cmd
                                set test_sleep_new(3) 0
                                set test_exit_after_cmd_new(3) 1
                                set test_order_new(3) 3
                                set test_new_conn_new(3) $test_new_connection
                                set test_prev_conn_new(3) 1
                                set test_in_round_new(3) 1
                                set test_stop_test_new(3) 1
#                        }
			if {$test_round_times==0} {
				set test_round_times_new 1
			} else {
	                        set test_round_times_new $test_round_times 
			}
                        set test_belong_group_new $test_belong_group
			
                        set test_state_new $test_state
			if {[string trim $test_state_new]==""} {set test_state_new "1"}
                        set test_owner_new $test_owner

		set sql_qur "select * from test_new where test_name='$test_name_new'"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

                log_info $info "sql_stat: $sql_qur" 2
                        if {$infect_line >0} {
                                log_info $info "Wrong! already have test $test_name_new,!" 3
				append test_name_new "_redu"
                        }

		set order_id 0
		for {set j 1} {$j<=3} {incr j +1} {
			incr order_id +1
			if {$test_dev_new($j)==""} {incr order_id -1; continue}
                        set sql_qur "INSERT INTO test_new (id,test_name,des,type,cmd,dev,negate,sleep,round_times,belong_group,state,exit_after_cmd,order,new_conn,prev_conn,in_round,stop_test,owner,group_id) values('','$test_name_new','$test_desc_new','$test_type_new','$test_cmd_new($j)','$test_dev_new($j)','$test_negate($j)','$test_sleep_new($j)','$test_round_times_new','$test_belong_group_new','$test_state_new','$test_exit_after_cmd_new($j)','$order_id','$test_new_conn_new($j)','$test_prev_conn_new($j)','$test_in_round_new($j)','$test_stop_test_new($j)','$test_owner_new','$group_id')"
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]
                        set k 0

                        if {$infect_line =="1"} {
                                log_info $info "Insert new test $test_name_new with order: $order_id into database successfully!" 4
                        } else {
                                log_info $info "Fail to insert into database !\n" 2
                                log_info $info "$infect_line" 2
                                return 0
                        }
		}
	}
	}
}
}
proc import_file {} {
	global info DB_NAME commit_import
	set w .import_file
	catch {destroy $w}
	toplevel $w
	wm title $w "Import data file"
	wm iconname $w "iconname?"
	positionWindow $w
	frame $w.content	
	frame $w.content.left
	frame $w.content.right
	frame $w.command
	pack $w.content -side top  -fill x -pady 2m
	pack $w.content.left $w.content.right -side left -expand yes -padx 10 -pady 10 -fill both
	pack $w.command -side bottom  -fill x -pady 2m

	label $w.content.left.file_name -text "Import File:" -padx 0 -width 16 -anchor e  
	label $w.content.left.db_name -text "Database Name:" -padx 0 -width 16 -anchor e 

	set file_name_entry [entry $w.content.right.file_name -width 45 -relief sunken ]
	set db_name_entry [entry $w.content.right.db_name -width 45 -relief sunken ]
	$file_name_entry delete 0 end
	$db_name_entry delete 0 end
	$db_name_entry insert 0 $DB_NAME
	

	button $w.command.confirm -text Confirm -command "import_env_hlp $file_name_entry $db_name_entry"
		
	button $w.command.browse -text Browse -command "select_file $file_name_entry; focus $w"
	button $w.command.cancel -text Cancel -command { set commit_import 0 } 
	pack $w.command.browse -side left -expand 1
	pack $w.command.confirm $w.command.cancel -side right -expand 1
	pack $w.content.left.file_name $w.content.left.db_name -side top -expand yes -pady 0 -anchor w
	pack $w.content.right.file_name $w.content.right.db_name -side top -expand yes -pady 0 -anchor w
	vwait commit_import
	catch {destroy $w}
	return commit_import
}
proc import_env_hlp {file_name_entry db_name_entry} {
	global info commit_import DB_SERVER DB_USER DB_PASS TREE_TB ENV_DEV ENV_TEST TEST column_array
	set file_name [$file_name_entry get]
	set new_db_name [$db_name_entry get]
	import_env $file_name $new_db_name
}
proc import_env {file_name new_db_name} {
	global info commit_import DB_SERVER DB_USER DB_PASS TREE_TB ENV_DEV ENV_TEST TEST column_array group_id
	set new_db_handle "no use anymore"
	#set new_db_handle [::mysql::connect -host $DB_SERVER -user $DB_USER -password $DB_PASS -db $new_db_name]
	log_info $info "file_name: $file_name; db_name: $new_db_name" 2
	if [catch {set filehandle [open $file_name r]} err_info] {
		log_info $info "Error to open file $file_name. Reason: $err_info" 2
		set commit_import 0
		return 0
	}
	set first_line [gets $filehandle]
	if {$first_line=="***tree***"} {
		set tree_line 0
		while {[set line [gets $filehandle]] != "***env_dev***" && ![eof $filehandle]} {
			log_info $info "line: $line" 2
			append tree_content $line
			append tree_content "\n"
			incr tree_line +1
			log_info $info "read tree line $tree_line" 2
			sleep 0.01
		}
		log_info $info "read $tree_line lines tree content" 3
		foreach record $tree_content {
			input_record $new_db_handle $record $new_db_name $TREE_TB
		}
		set tree_line 0
		unset tree_content
		if {$line=="***env_dev***"} {
                      while {[set line [gets $filehandle]] != "***env_test***" && ![eof $filehandle]} {
                              log_info $info "line: $line" 2
                              append tree_content $line
                              append tree_content "\n"
                              incr tree_line +1
                              log_info $info "read env_dev line $tree_line" 2
                      }
                      log_info $info "read $tree_line lines env_dev content" 3
                      foreach record $tree_content {
                              input_record $new_db_handle $record $new_db_name $ENV_DEV
                      }
		}
                set tree_line 0
		unset tree_content
                if {$line=="***env_test***"} {
                      while {[set line [gets $filehandle]] != "***test***" && ![eof $filehandle]} {
                              log_info $info "line: $line" 2
                              append tree_content $line
                              append tree_content "\n"
                              incr tree_line +1
                              log_info $info "read env_test line $tree_line" 2 
                      }
                      log_info $info "read $tree_line lines env_test content" 3
                      foreach record $tree_content {
                              input_record $new_db_handle $record $new_db_name $ENV_TEST
                      }
                }
                set tree_line 0
                unset tree_content
                if {$line=="***test***"} {
                      while {[set line [gets $filehandle]] != "***test***" && ![eof $filehandle]} {
                              log_info $info "line: $line" 2
                              append tree_content $line
                              append tree_content "\n"
                              incr tree_line +1
                              log_info $info "read test line $tree_line" 2
                      }
                      log_info $info "read $tree_line lines test content" 3
                      foreach record $tree_content {
                              input_record $new_db_handle $record $new_db_name $TEST
                      }
                }

	} else {
		log_info $info "file format is wrong, first line is not ***tree***" 2
		set commit_import 0
		return 0
	}
	set commit_import 1
	return 1
}
proc input_record {new_db_handle record new_db_name table_name} {
	global info column_array TREE_TB ENV_DEV ENV_TEST TEST group_id
	if {$record=="\n"} {
		log_info $info "ingore new line record" 2
		return 1
	}

	###substitute id
	if {[regexp {('')\s(.*)} $record no_use id_value record_value]==1} {
		set value_string "'',"
		foreach column_value $record_value {
			set column_value [handle_string_special $column_value]
			append value_string "'$column_value"
			append value_string "',"
		}
		set value_string [trimend $value_string ","]
                #this line is for upgrading, if importing file exported from old db which donot have group_id in it, then we need add it here
                if {$column_value != "$group_id"} {append value_string ",'$group_id"; append value_string "'"}
		#delete old record with same key value
		#delete old tree record
		if {$table_name=="$TREE_TB"} {
			log_info $info "record: $record" 4
			set name [lindex $record 1]
			set parentID [lindex $record 2]
			set sql_qur "DELETE FROM $table_name where (name='$name' and parentID='$parentID' and group_id='$group_id')"
                        set sky_response [mysql_pack $sql_qur $new_db_name ]
                        set infect_line [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]
                        set k 0

                        log_info $info "$sql_qur" 4
                        if {$infect_line =="1"} {
                                log_info $info "Delete $infect_line tree record with name=$name and parentID=$parentID!" 3
                        } else {
                                log_info $info "No tree record with name=$name and parentID=$parentID!" 3
                        }
		}
                #delete old env_dev record
                if {$table_name=="$ENV_DEV"} {
                        set env_name [lindex $record 1]
                        set dev [lindex $record 3]
                        set sql_qur "DELETE FROM $table_name where (env_name='$env_name' and dev='$dev' and group_id='$group_id')"
                        set sky_response [mysql_pack $sql_qur $new_db_name ]
                        set infect_line [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]
                        set k 0

                        log_info $info "$sql_qur" 4
                        if {$infect_line =="1"} {
                                log_info $info "Delete $infect_line $ENV_DEV record with env_name=$env_name and dev=$dev!" 3
                        } else {
                                log_info $info "No $ENV_DEV record with env_name=$env_name and dev=$dev!" 3
                        }
                }
                #delete old env_test record
                if {$table_name=="$ENV_TEST"} {
                        set env_name [lindex $record 1]
                        set test_name [lindex $record 2]
                        set sql_qur "DELETE FROM $table_name where (env_name='$env_name' and test_name='$test_name' and group_id='$group_id')"
                        set sky_response [mysql_pack $sql_qur $new_db_name ]
                        set infect_line [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]
                        set k 0

                        log_info $info "$sql_qur" 4
                        if {$infect_line =="1"} {
                                log_info $info "Delete $infect_line $ENV_TEST record with env_name=$env_name and test_name=$test_name!" 3
                        } else {
                                log_info $info "No $ENV_TEST record with env_name=$env_name and test_name=$test_name!" 3
                        }
                }
                #delete old test record
                if {$table_name=="$TEST"} {
                        set test_name [lindex $record 1]
                        set order [lindex $record 12]
                        set sql_qur "DELETE FROM $table_name where (test_name='$test_name' and `order`='$order' and group_id='$group_id')"
                        set sky_response [mysql_pack $sql_qur $new_db_name ]
                        set infect_line [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]

                        log_info $info "$sql_qur" 4
                        if {$infect_line =="1"} {
                                log_info $info "Delete $infect_line $TEST record with test_name=$test_name and `order`=$order!" 3
                        } else {
                                log_info $info "No $TEST record with test_name=$test_name and `order`=$order!" 3
                        }
                }
                #Insert new record
	        set sql_qur "INSERT INTO $table_name values($value_string)"
                set sky_response [mysql_pack $sql_qur $new_db_name ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

        	log_info $info "$sql_qur" 4
	        if {$infect_line =="1"} {
        	        log_info $info "Insert one record Into table $table_name successfully!" 3
			return 1
	        } else {
        	        log_info $info "Fail to insert record into table $table_name!" 2
			return 0
	        }
	} else {
		log_info $info "record format is wrong, first item should be blank for ID" 2
		return 0
	}
}
proc save_to_file {widget} {
        set types {
                {{Sql Files}  {.env} }
                {{All Files}  *      }
        }
        set file_name [tk_getSaveFile -filetypes $types]
        $widget insert 0 $file_name
}
proc select_file {widget} {
	set types {
		{{Sql Files}  {.env} }
		{{All Files}  *      }
	}
	set file_name [tk_getOpenFile -filetypes $types]
	$widget insert 0 $file_name
}
proc document_env {cur_env doc_mode} {
	#Create testcases document by testcases description
        global DB_NAME info SCRIPT_DIR TREE_TB ENV_DEV ENV_TEST TEST commit_document

        set w .export_file
        catch {destroy $w}
        toplevel $w
        wm title $w "Export testcases document for $cur_env"
        wm iconname $w "iconname?"
        positionWindow $w
        frame $w.content
        frame $w.content.left
        frame $w.content.right
        frame $w.command
        pack $w.content -side top  -fill x -pady 2m
        pack $w.content.left $w.content.right -side left -expand yes -padx 10 -pady 10 -fill both
        pack $w.command -side bottom  -fill x -pady 2m

        label $w.content.left.file_name -text "Export to File:" -padx 0 -width 16 -anchor e
        label $w.content.left.db_name -text "Export Source env:" -padx 0 -width 16 -anchor e

        set file_name_entry [entry $w.content.right.file_name -width 45 -relief sunken ]
        set exp_env_entry [entry $w.content.right.db_name -width 45 -relief sunken ]
        cd $SCRIPT_DIR
        set env_name "testcases_doc/"
        append env_name [string map {/ _ . _} $cur_env]
	append env_name ".$doc_mode"
        $file_name_entry delete 0 end
        $file_name_entry insert 0 $env_name
        $exp_env_entry delete 0 end
        $exp_env_entry insert 0 $cur_env


        button $w.command.confirm -text Confirm -command "document_env_file $file_name_entry $exp_env_entry $doc_mode"

        button $w.command.browse -text Browse -command "$file_name_entry delete 0 end; save_to_file $file_name_entry; focus $w"
        button $w.command.cancel -text Cancel -command { set commit_document 0 }
        pack $w.command.browse -side left -expand 1
        pack $w.command.confirm $w.command.cancel -side right -expand 1
        pack $w.content.left.file_name $w.content.left.db_name -side top -expand yes -pady 0 -anchor w
        pack $w.content.right.file_name $w.content.right.db_name -side top -expand yes -pady 0 -anchor w
        vwait commit_document
        catch {destroy $w}
        return commit_document
}
proc export_env {cur_env} {
	global DB_NAME info SCRIPT_DIR TREE_TB ENV_DEV ENV_TEST TEST commit_export

        set w .export_file
        catch {destroy $w}
        toplevel $w
        wm title $w "Export data file"
        wm iconname $w "iconname?"
        positionWindow $w
        frame $w.content
        frame $w.content.left
        frame $w.content.right
        frame $w.command
        pack $w.content -side top  -fill x -pady 2m
        pack $w.content.left $w.content.right -side left -expand yes -padx 10 -pady 10 -fill both
        pack $w.command -side bottom  -fill x -pady 2m

        label $w.content.left.file_name -text "Export to File:" -padx 0 -width 16 -anchor e
        label $w.content.left.db_name -text "Export Source env:" -padx 0 -width 16 -anchor e

        set file_name_entry [entry $w.content.right.file_name -width 45 -relief sunken ]
        set exp_env_entry [entry $w.content.right.db_name -width 45 -relief sunken ]
	cd $SCRIPT_DIR
	set env_name "../env_repository/"
	append env_name [string map {/ _ . _} $cur_env]
	append env_name ".env"
        $file_name_entry delete 0 end
	$file_name_entry insert 0 $env_name
        $exp_env_entry delete 0 end
        $exp_env_entry insert 0 $cur_env


        button $w.command.confirm -text Confirm -command "export_env_file_help $file_name_entry $exp_env_entry"

        button $w.command.browse -text Browse -command "$file_name_entry delete 0 end; save_to_file $file_name_entry; focus $w"
        button $w.command.cancel -text Cancel -command { set commit_export 0 }
        pack $w.command.browse -side left -expand 1
        pack $w.command.confirm $w.command.cancel -side right -expand 1
        pack $w.content.left.file_name $w.content.left.db_name -side top -expand yes -pady 0 -anchor w
        pack $w.content.right.file_name $w.content.right.db_name -side top -expand yes -pady 0 -anchor w
        vwait commit_export
        catch {destroy $w}
        return commit_export
}
proc document_env_file {file_name_entry exp_env_entry doc_mode} {
        global DB_NAME info SCRIPT_DIR TREE_TB ENV_DEV ENV_TEST TEST commit_document document_env
        set file_name [$file_name_entry get]
        set cur_env [$exp_env_entry get]
        set document_env $cur_env
        cd $SCRIPT_DIR
        set cur_dir [eval pwd]
        if [catch {set filehandle [open $file_name w]} err_info] {
                log_info $info "Error to open file $file_name. Reason: $err_info" 2
                set commit_document 0
                return 0
        }
	set time [clock format [clock second] -format "%b %d,%Y"]
        puts $filehandle "<br>"
        puts $filehandle "***Testcases document for $cur_env, created by autotestnet at $time***"
	if {$doc_mode=="table"} {
	        puts $filehandle "%EDITTABLE{ format = \"|textarea, 4x26 | textarea, 3x35 | textarea, 3x40| text,5 |\"}%"
        	puts $filehandle "| *Testcase catalog* | *Object* | *Test content* | *Type* |"
	} else {
		puts $filehandle "%TOC%"
	}
	set steps_old ""
	set steps_new ""
	set spawn_env ""
        document_create_env $cur_env $filehandle $doc_mode $steps_old steps_new $spawn_env
        if [catch {close $filehandle} err_info] {
                log_info $info "Error to close file. Reason: $err_info" 2
                set commit_document 0
                return 0
        }
	set commit_document 1
}
proc puts_wiki_record {filehandle name parentid desc state owner run_times doc_env} {
	global info
	log_info $info "parentid: $parentid; doc_env: $doc_env" 2
	set parentid [string range $parentid [string length $doc_env] end]
	log_info $info "parentid: $parentid; doc_env: $doc_env" 2    
	#remove first level
	if {[string first / $parentid]!=-1} {
		set sub_env [string range $parentid [expr [string first / $parentid]+1] end]
		set sub_env "$sub_env/$name"
	} else {
		set sub_env "$name"
	}
	log_info $info "sub_env:$sub_env" 2
	set new_sub_env [string map {\/ "\/ "} $sub_env]
#	Add space for each 25 characters
#	while {[string length $sub_env]>25} {
#		append new_sub_env [string range $sub_env 0 24]
#		append new_sub_env " "
#		set sub_env [string range $sub_env 25 end]
#	}
#	append new_sub_env $sub_env
	log_info $info "new_sub_env:$new_sub_env" 2
	#Analyze desc
	set object_start [string first "<Object>" $desc]
	set content_start [string first "<Test Content>" $desc]
	set notes_start [string first "<Notes>" $desc]
	set object [string range $desc [expr $object_start+9] [expr $content_start-2]]
	set object [string map {\n "<br>" \r "  "} $object]
	set object [string trim $object ]
	set test_content [string range $desc [expr $content_start+15] [expr $notes_start-2]]
	set test_content [string map {\n "<br>" \r "  "} $test_content]
        set test_content [string trim $test_content]
	if {$object==""} {set object "N/A"}
	if {$test_content==""} {set test_content "N/A"}
	#handle state field
	switch $state {
        	0 {set type "Ignore"}
        	1 {set type "Normal"}
        	5 {set type "Package"}
        	default {set type "Others"}
	}
	puts $filehandle "|$new_sub_env|$object|$test_content|$type|"
}
proc document_create_sub_env {cur_env filehandle doc_mode steps_old steps_new spawn_env} {
	global DB_NAME info TREE_TB document_env ENV_TEST TEST group_id
	upvar $steps_new steps_whole
	set steps_whole "$steps_old"

        set son_env [get_son_env $cur_env]
        set parent_env [get_parent_env $cur_env]
        log_info $info "Document_create_sub_env: cur_env: $cur_env; son_env: $son_env; parent_env: $parent_env " 2
        set sql_qur "SELECT * from $TREE_TB where ParentID='$parent_env' and name='$son_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line !="0"} {
                log_info $info "Document_create_sub_env: Found $infect_line tree records" 3
		if {$infect_line == 1} {
                        set cur_row [lindex $sql_ret_str $k]
                        set name [lindex $cur_row 1]
                        set parentid [lindex $cur_row 2]
                        set desc [lindex $cur_row 3]
                        set state [lindex $cur_row 4]
                        set owner [lindex $cur_row 5]
                        set run_times [lindex $cur_row 6]
			if {$doc_mode=="table"} {
				puts_wiki_record $filehandle $name $parentid $desc $state $owner $run_times $document_env
			} elseif {$doc_mode=="singlecase"} {
                               #Analyze desc
                               set object_start [string first "<Object>" $desc]
                               set content_start [string first "<Test Content>" $desc]
                               set notes_start [string first "<Notes>" $desc]
                               set object [string range $desc [expr $object_start+9] [expr $content_start-2]]
#                                set object [string map {\n "<br>" \r "  "} $object]
                               set object [string trim $object ]
                               set test_content [string range $desc [expr $content_start+15] [expr $notes_start-2]]
                               set test_content [string map {\n "<br>" \r "  "} $test_content]
                               set test_content [string trim $test_content]
                               if {$object==""} {set object "N/A"}
                               if {$test_content==""} {set test_content "N/A"}
                                                set env_name $cur_env
                                                if {[string first $document_env $cur_env]==0} {
                                                        set env_name [string range $cur_env [expr [string length $document_env]+1] end]
                                                }
#						set levels [expr [llength [file split $env_name]] -0]
#						if {$levels>5} {set levels 5}
#						set pre_string "---"
#						for {set i 1} {$i<=$levels} {incr i +1} {
#							append pre_string "+"
#						}
#						set itemline "$pre_string"
#						append itemline $env_name
#						puts $filehandle $itemline
#						puts $filehandle $test_content
#						puts $filehandle "---------------"
 


                               append steps_whole "      * $env_name<br>"
                               #append steps_whole "      * $cur_env<br>"
                               append steps_whole "$test_content\n"
                               ###Check if there is a test element in current env
                               set sql_qur "SELECT * FROM $ENV_TEST WHERE (env_name='$cur_env' and group_id='$group_id') order by env_name,test_name"
                               set sky_response [mysql_pack $sql_qur $DB_NAME ]
                               set infect_line [lindex $sky_response 0]
                               set sql_ret_str [lindex $sky_response 1]
                               set k 0

                               if {$infect_line != "0"} {
                                        #There is test in current env, then we need to export testcases for each test
                                        log_info $info "Found $infect_line env_test records. Then we need to create $infect_line testcases in document" 3
                                        for {set i 1} {$i<=$infect_line} {incr i +1} {
                                              set record($i) [lindex $sql_ret_str $k]
                                              incr k +1
					}
                               		for {set i 1} {$i<=$infect_line} {incr i +1} {
                				set test_env [lindex $record($i) 1]
						if {[string first $document_env $test_env]==0} {
		   				        set test_env [string range $test_env [string length $document_env] end]
						}
			                        set test_name [lindex $record($i) 2]
			                        set test_exp_result [lindex $record($i) 4]
						if {$test_exp_result==0} {
							set test_exp_result "PASS"
						} else {
							set test_exp_result "FAIL"
						}
			                        set test_description [string trim [lindex $record($i) 5]]
			                        set test_state_value [lindex $record($i) 6]
						switch $test_state_value {
							"0" {set test_state "Donot run it"}
							"1" {set test_state "Run it and care result"}
							"2" {set test_state "Run it and do not care result"}
							default {set test_state "Unknown"}
						}
						set testcase_name $spawn_env
						if {[string first $document_env $spawn_env]==0} {
		   				        set testcase_name [string range $spawn_env [string length $document_env] end]
						}
						append testcase_name "/$test_env"
						append testcase_name "/$test_name"
						puts $filehandle "---++Test Case: $testcase_name"
						#puts $filehandle "---++++++Test Case: $testcase_name"
						puts $filehandle "   * *Expect result: $test_exp_result*"
						puts $filehandle "   * *Description:$test_description*"
						puts $filehandle "   * *Autotest flag: $test_state*"

						if {$i!=1} {
							set steps_whole1 "Same as previous case\n"
						} else {
							set steps_whole1 "$steps_whole"
						}
						puts $filehandle "   * *Environment setting:*"
						puts $filehandle "$steps_whole1\n"
						# get description from TEST table
						set test_des ""
                                                set sql_qur "SELECT des FROM $TEST WHERE test_name='$test_name' and group_id='$group_id' order by `order`"
                                                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                                                set infect_line1 [lindex $sky_response 0]
                                                set sql_ret_str [lindex $sky_response 1]
                                                set k 0

                                                if {$infect_line1 !="0"} {
                                                        log_info $info "Found $infect_line1 test records for test:$name" 3
                                                        set test_des [lindex $sql_ret_str $k]
                					set test_des [lindex $test_des 0]
							log_info $info "test_des: $test_des" 2
                                                } else {
                                                        log_info $info "Warning, cannot find test $name in test table when trying to create testcase document!" 2
                                                }
                       				set test_des [string map {\n "<br>" \r "  "} $test_des]
                                                puts $filehandle "   * *Test Element Name: $test_name*"
                                                puts $filehandle "   * *Test Step:* <br>"
                                                puts $filehandle "      * $test_des<br>"
						puts $filehandle "--------------------------------------<br>"
                                      }
                               } else {
                                        #No testcases in current env, then we need to append test_steps of current env
                                       log_info $info "No testcases need to created document in env $cur_env!" 2
                               }
				if {$state=="5"} {
					#This is a package, need to dig in it
					log_info $info "create testcases for package $name under $parentid" 2

					document_create_env $name $filehandle $doc_mode $steps_whole steps_new $parentid
				}
			}
		} else {
			log_info $info "Document_create_sub_env: there are more than 1 record for ParentID='$parent_env' and name='$son_env'" 3
			log_info $info "Document_create_sub_env: only handle the first one.Should contact manager to delete others" 3
		}
        } else {
                log_info $info "Document_create_sub_env:no tree record for ParentID='$parent_env' and name='$son_env'" 3
        }
}
proc document_create_env {cur_env filehandle doc_mode steps_whole_old steps_whole_new spawn_env} {
	global DB_NAME info TREE_TB group_id user_id
	upvar $steps_whole_new steps_whole
	set old_env $cur_env
	set steps_whole $steps_whole_old
	document_create_sub_env $cur_env $filehandle $doc_mode $steps_whole steps_new $spawn_env
	set steps_whole_old $steps_new

        set sql_qur "SELECT name from $TREE_TB where ParentID='$cur_env' and group_id='$group_id' ORDER BY Parentid, name"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line != "0"} {
                log_info $info "Found $infect_line tree records" 3
                for {set i 1} {$i<=$infect_line} {incr i +1} {
                        set cur_row [lindex $sql_ret_str $k]
                        incr k +1
                        set name($i) [lindex $cur_row 0]
		}
            	for {set j 1} {$j<$i} {incr j +1} {
			set sub_env "$cur_env/$name($j)"
			set steps_whole_old $steps_new
			set a1 "nouse"
			document_create_env $sub_env $filehandle $doc_mode $steps_whole_old a1 $spawn_env
		}
#		log_info $info "steps_whole_old: $steps_whole_old." 2
#		set steps_whole_old $a1
#		log_info $info "steps_whole_old: $steps_whole_old." 2
        } else {
                log_info $info " no other sub_env under $cur_env" 3
        }
        set cur_env $old_env
        log_info $info "********************************************************************" 2
        log_info $info "*finish to create document for $cur_env" 2
        log_info $info "********************************************************************" 2
}
proc export_env_file_help {file_name_entry exp_env_entry} {
        set file_name [$file_name_entry get]
        set cur_env [$exp_env_entry get]
	export_env_file $file_name $cur_env
}
proc export_env_file {file_name cur_env} {
	global DB_NAME info SCRIPT_DIR TREE_TB ENV_DEV ENV_TEST TEST commit_export
	eval cd $SCRIPT_DIR
        set cur_dir [eval pwd]
	if [catch {set filehandle [open $file_name w]} err_info] {
		log_info $info "Error to open file $file_name. Reason: $err_info" 2
		set commit_export 0
		return 0
	}
	puts $filehandle "***tree***"
	set results {}
	set newline "\n"
	set sql_qur "SELECT * FROM $TREE_TB WHERE (((Parentid like '$cur_env/%') or (parentid='$cur_env') or (name='$cur_env' and parentid='0')) and group_id='$group_id') order by parentid,name"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0


        if {$infect_line !="0"} {
                log_info $info "Found $infect_line tree records" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
			set record [lindex $sql_ret_str $k]
                        incr k +1
			if {[regexp {(\d+)\s(.*)} $record no_use id_value record_value]==1} {
				set record "'' $record_value"
				lappend results $record
				lappend results $newline
			} else {
				log_info $info "Warning! no ID value in record. ignore it. record: $record" 2
			} 
		}
        } else {
                log_info $info "No tree records need be exported!" 2
        }
	puts $filehandle $results
	puts $filehandle "***env_dev***"
	set results {}
	set sql_qur "SELECT * FROM $ENV_DEV WHERE (((env_name like '$cur_env/%') or (env_name='$cur_env')) and (group_id='$group_id')) order by env_name,dev"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line !="0"} {
                log_info $info "Found $infect_line env_dev records" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
                        set record [lindex $sql_ret_str $k]
                        incr k +1
                        if {[regexp {(\d+)\s(.*)} $record no_use id_value record_value]==1} {
                                set record "'' $record_value"
                                lappend results $record
				lappend results $newline
                        } else {
                                log_info $info "Warning! no ID value in record. ignore it. record: $record" 2
                        }
		}
        } else {
                log_info $info "No env_dev records need be exported!" 2
        }

	puts $filehandle $results
	puts $filehandle "***env_test***"
	set results {}
	set record ""
	set test_list {}
	set sql_qur "SELECT * FROM $ENV_TEST WHERE (((env_name like '$cur_env/%') or (env_name='$cur_env')) and (group_id='$group_id')) order by env_name,test_name"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line !="0"} {
                log_info $info "Found $infect_line env_test records" 3
		for {set i 1} {$i<=$infect_line} {incr i +1} {
                        set record [lindex $sql_ret_str $k]
                        incr k +1
                        if {[regexp {(\d+)\s(.*)} $record no_use id_value record_value]==1} {
                                set record "'' $record_value"
                                lappend results $record
				lappend results $newline
				lappend test_list [lindex $record 2]
                        } else {
                                log_info $info "Warning! no ID value in record. ignore it. record: $record" 2
                        }
		}
        } else {
                log_info $info "No env_test records need be exported!" 2
        }

	puts $filehandle $results

        puts $filehandle "***test***"
	set results {}
	foreach name $test_list {
		set sql_qur "SELECT * FROM $TEST WHERE test_name='$name' and group_id='$group_id' order by `order`"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

                if {$infect_line != "0"} {
                        log_info $info "Found $infect_line test records for test:$name" 3
                        for {set i 1} {$i<=$infect_line} {incr i +1} {
                                set record [lindex $sql_ret_str $k]
                                incr k +1
                                if {[regexp {(\d+)\s(.*)} $record no_use id_value record_value]==1} {
                                        set record "'' $record_value"
                                        lappend results $record
					lappend results $newline
                                } else {
                                        log_info $info "Warning! no ID value in record. ignore it. record: $record" 2
                                }
                        }
                } else {
                        log_info $info "Warning, cannot find test $name in test table!" 2
                }
	}
	puts $filehandle $results

	if [catch {close $filehandle} err_info] {
                log_info $info "Error to close file. Reason: $err_info" 2
		set commit_export 0
		return 0
        }
	set commit_export 1
	return $commit_export
}
proc paste_env {cur_env cp_env} {
	global DB_NAME info
	after idle {.dialog1.msg configure -wraplength 4i}
	set i [tk_dialog .dialog1 "Confirm to paste env" " You selected to paste env from $cp_env to $cur_env, that means all contents under $cp_env will be copied to $cur_env, Are you sure?" info 0 OK Cancel]
	switch $i {
	    0 {
	    	log_info $info "Start to paste env from $cp_env to $cur_env" 2
		set son_env [lindex [split $cp_env "/"] end]
		set parent_env [string range $cp_env 0 [expr [string first $son_env $cp_env]-2]] 
		if {[string trim $parent_env]==""} { set parent_env "0"}
   		log_info $info "son_env: $son_env; parent_env: $parent_env; cur_env: $cur_env" 2
		confirm_chg_name_env $parent_env $son_env $cur_env $son_env 1
	      }
	    1 {log_info $info "Cancel paste" 2}
	}
	


}
proc chg_name_env {cur_env} {
	global DB_NAME info commit_chg_env_name
        set son_env [get_son_env $cur_env]
        set parent_env [get_parent_env $cur_env]
        log_info $info "cur_env: $cur_env; son_env: $son_env; parent_env: $parent_env " 2

        set w .chg_name 
        catch {destroy $w}
        toplevel $w
        wm title $w "Change name of $son_env in $parent_env"
        wm iconname $w "iconname?"
        positionWindow $w
        frame $w.left
        frame $w.right
        frame $w.command
        pack $w.left $w.right -side left -expand yes -padx 10 -pady 10 -fill both
        pack $w.command -side bottom  -fill x -pady 2m

        label $w.left.old_name -text "Old env name" -padx 0 -width 15 -anchor e

        label $w.left.new_name -text "New env name" -padx 0 -width 15 -anchor e
	
	label $w.right.old_name -text "$son_env" -relief sunken -width 35 -anchor e
        entry $w.right.new_name -width 35 -relief sunken 

        button $w.command.confirm -text Confirm -command [list help_chg_name_env $parent_env $son_env $parent_env $w.right.new_name 0]
        button $w.command.cancel -text Cancel -command [list set commit_chg_env_name 0]
        pack $w.command.confirm $w.command.cancel -side left -expand 1
        pack $w.left.old_name $w.left.new_name -side top -expand yes -pady 2 -anchor w
        pack $w.right.old_name $w.right.new_name -side top -expand yes -pady 2 -anchor w
        vwait commit_chg_env_name;
	catch {destroy $w}
        return $commit_chg_env_name
}	
proc rem_env {cur_env} {
	global DB_NAME row1 info TREE_TB ENV_DEV ENV_TEST TEST
        set son_env [get_son_env $cur_env]
        set parent_env [get_parent_env $cur_env]
        log_info $info "In rem_env. cur_env: $cur_env; son_env: $son_env; parent_env: $parent_env " 2

        after idle {.dialog1.msg configure -wraplength 4i}
        set i [tk_dialog .dialog1 "Confirm remove env" " You select to remove env $cur_env, that means \
        all configuration under $cur_env will be deleted, Are you sure?" info 0 OK Cancel]
        switch $i {
            0 {
                if {[rem_env_exec $cur_env]==1} {
                        log_info $info "remove $cur_env successfully" 2
                } else {
                        log_info $info "Failed to remove $cur_env " 2
                }
              }
            1 {log_info $info "Cancel Changing Device" 2}
        }
        catch {destroy $widget_win}
}
proc rem_env_exec {cur_env} {
	global DB_NAME row1 info TREE_TB ENV_DEV ENV_TEST TEST group_id
        set son_env [get_son_env $cur_env]
        set parent_env [get_parent_env $cur_env]

	#Remove Tree
	set sql_qur "DELETE FROM $TREE_TB WHERE (((name='$son_env' and Parentid='$parent_env') or (Parentid='$cur_env') or (Parentid like '$cur_env/%')) and (group_id='$group_id'))"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line != "0"} {
                log_info $info "Delete $cur_env from Tree table successfully! $infect_line" 3
		Tree:delitem .f.w /$cur_env 
        } else {
                log_info $info "Fail to delete $cur_env from database ! $infect_line" 2
        }
	#Remove env_dev
        set sql_qur "DELETE FROM $ENV_DEV WHERE (((env_name like '$cur_env/%') or (env_name='$cur_env')) and (group_id='$group_id'))"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line !="0"} {
                log_info $info "Delete $cur_env from Env_dev table successfully! $infect_line" 3
        } else {
                log_info $info "Fail to delete $cur_env from database ! $infect_line" 2
        }
        #Remove env_test
        set sql_qur "DELETE FROM $ENV_TEST WHERE (((env_name like '$cur_env/%') or (env_name='$cur_env')) and (group_id='$group_id'))"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line != "0"} {
                log_info $info "Delete $cur_env from Env_test successfully! $infect_line" 3
        } else {
                log_info $info "Fail to delete $cur_env from database ! $infect_line" 2
        }
	return 1
}
proc input_dev_to_db {} {
	global DB_PRV_NAME DB_NAME row1 DEV_TB info user_id
	for {set i 1} {$i<=7} {incr i +1} {
		set row1($i) [string map {\" \\" \' \\'} $row1($i)]
	}
        set sql_qur "SELECT * from $DEV_TB where name='$row1(1)' and user_id='$user_id'"

        set sky_response [mysql_pack $sql_qur $DB_PRV_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

	if {$parent_line > "0"} {	
		log_info $info "found device $row1(1) in DEV_TB" 6
		log_info $info "row1(2): $row1(2)" 2
		set sql_qur "UPDATE $DEV_TB SET ip='$row1(3)',des='$row1(2)',access_mode='$row1(4)',access_user='$row1(5)',access_pass='$row1(6)',access_port='$row1(7)',type='$row1(8)' WHERE name='$row1(1)' and user_id='$user_id'"
                set sky_response [mysql_pack $sql_qur $DB_PRV_NAME ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

                if {$infect_line == "1"} {
                        log_info $info "UPDATE device $row1(1) successfully!" 2
			return 1
                } else {
                        log_info $info "Failed to update $row1(1) in database $DEV_TB !" 1
                        log_info $info "infect line: $infect_line . should be 1 " 1
			return 0
                }
	} else {
		log_info $info "Cannot found device $row1(1), Add it as new device" 6 
		set sql_qur "INSERT INTO $DEV_TB (id,name,des,ip,access_mode,access_user,access_pass,access_port,type,user_id) values ('','$row1(1)','$row1(2)','$row1(3)','$row1(4)','$row1(5)','$row1(6)','$row1(7)','$row1(8)','$user_id')"

                set sky_response [mysql_pack $sql_qur $DB_PRV_NAME ]
                set infect_line [lindex $sky_response 0]

		log_info $info "$sql_qur" 6
		if {$infect_line == "1"} {
			log_info $info "Insert $row1(1) into device database successfully!\n" 3
			return 1
		} else {
			log_info $info "Failed to insert $row1(1) into device database !\n" 2
			log_info $info "$infect_line" 2
			return 0
		}
	}
}
proc dele_dev_in_db { dev_name } {
	global DB_PRV_NAME row1 DEV_TB info user_id
        set sql_qur "DELETE FROM $DEV_TB WHERE name='$dev_name' and user_id='$user_id'"
        set sky_response [mysql_pack $sql_qur $DB_PRV_NAME ]
        set infect_line [lindex $sky_response 0]

        $info insert end "$sql_qur"
        if {$infect_line == "1"} {
                log_info $info "Delete device $DEV_TB in database successfully!\n" 3
                $info see end
        } else {
                log_info $info "Fail to delete $DEV_TB in database !\n" 2
                log_info $info "$infect_line" 2
        }
}
proc input_test_group_to_db {} {
        global DB_NAME row1 DEV_TB info TEST TEST_GROUP row_test_group group_id user_id
        for {set i 1} {$i<=4} {incr i +1} {
                set row1($i) [string map {\" \\" \' \\' \( \\\( \) \\\)} $row_test_group($i)]
        }
	log_info $info "row_test_group(3): $row_test_group(3)" 2
#add ";" to the end of  test_list and env_list
	if {[string index $row_test_group(3) end]!=";"} {
		set row_test_group(3) [append row_test_group(3) ";"]
	log_info $info "row_test_group(3): $row_test_group(3)" 2
	} 
	if {[string index $row_test_group(4) end]!=";"} {
		set row_test_group(4) [append row_test_group(4) ";"]
	} 

	set sql_qur "SELECT * FROM $TEST_GROUP where name='$row_test_group(1)' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

	log_info $info $sql_qur 6
	if {$infect_line > 0} {
#update old record
                log_info $info "found test $row_test_group(1) in $TEST_GROUP" 6
                set sql_qur "UPDATE $TEST_GROUP SET test_list='$row_test_group(3)',des='$row_test_group(2)',env_list='$row_test_group(4)' WHERE name='$row_test_group(1)' and group_id='$group_id'"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

		log_info $info $sql_qur 6
                if {$infect_line == "1"} {
                        log_info $info "UPDATE $TEST_GROUP $row_test_group(1) successfully!" 2
                        return 1
                } else {
                        log_info $info "Fail to insert $row_test_group(1) into table $TEST_GROUP !" 2
                        return 0
                }
	} else {
#add new record
                log_info $info "Cannot found test $row1(1), Add it as new test" 6
	        set sql_qur "INSERT INTO $TEST_GROUP (id,name,des,test_list,env_list,group_id) values ('','$row_test_group(1)','$row_test_group(2)','$row_test_group(3)','$row_test_group(4)','$group_id')"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

        	log_info $info "$sql_qur" 6
	        if {$infect_line == "1"} {
        	        log_info $info "Insert new test $row_test_group(1) Into table $TEST_GROUP successfully!\n" 3
			return 1
	        } else {
        	        log_info $info "Fail to $row_test_group(1) into table $TEST_GROUP !" 2
			return 0
	        }
	}
}

proc input_test_to_db {des_txt cmd_txt_list_widget} {
        global DB_NAME row1 DEV_TB info TEST operator dev_cmd_grp_no group_id user_id
	upvar $cmd_txt_list_widget cmd_txt_widget_list
	log_info $info "dev_cmd_grp_no: $dev_cmd_grp_no" 2
	if {[string trim $row1(1,1)]==""} {
		log_info $info "test name can not be null, return" 2
		return 0
	}
	set row1(1,2) [string trim [$des_txt get 1.0 end]]
	set i 1
	foreach cmd_txt_widget $cmd_txt_widget_list {
		log_info $info "widget: $cmd_txt_widget" 2
		set row1($i,4) [string trim [$cmd_txt_widget get 1.0 end]]
		incr i +1
	}
        for {set order_no 1} {$order_no<=$dev_cmd_grp_no} {incr order_no +1} {
                #set row1($order_no,4) [string map {\" \\" \' \\' \( \\\( \) \\\) \\\\ \\\\\\\\} $row1($order_no,4)]
                set row1($order_no,4) [handle_string_special $row1($order_no,4)]
        	set sql_qur "SELECT owner FROM $TEST where test_name='$row1(1,1)' and `order`='$row1($order_no,12)' and group_id='$group_id'"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

        	log_info $info $sql_qur 6
        	if {$infect_line > 0} {
        		set old_owner [lindex $sql_ret_str $k]
                        incr k +1
        		#check relation
        		#set ismanager [chk_relation $old_owner $operator]
        		set ismanager 1
        		if {$ismanager==1} {
        			#update old record
                        	log_info $info "found test $row1(1,1) in $TEST" 6
                        	set sql_qur "UPDATE $TEST SET des='$row1(1,2)',`type`='$row1(1,3)',cmd='$row1($order_no,4)',dev='$row1($order_no,5)',negate='$row1($order_no,6)',sleep='$row1($order_no,7)',round_times='$row1(1,8)',belong_group='$row1(1,9)',state='$row1(1,10)',exit_after_cmd='$row1($order_no,11)',new_conn='$row1($order_no,13)',prev_conn='$row1($order_no,14)',in_round='$row1($order_no,15)',stop_test='$row1($order_no,16)',owner='$row1($order_no,17)' WHERE test_name='$row1(1,1)' and `order`='$row1($order_no,12)' and group_id='$group_id'"
                                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                                set infect_line [lindex $sky_response 0]
                                set sql_ret_str [lindex $sky_response 1]

        			log_info $info $sql_qur 6
                        	if {$infect_line =="1"} {
                                	log_info $info "UPDATE test $row1(1,1) with order: $order_no successfully!" 2
        	                } else {
                	                log_info $info "Fail to update test $row1(1,1) in table $TEST !" 1
                        	        log_info $info "infect line: $infect_line . should be 1 " 1
                                	return 0
                        	}
        		} else {
        			log_info $info "Operator $operator does not have privilege to change $old_owner 's test element " 2
        			return 0
        		}
		} elseif {$row1($order_no,12)=="0"} {
			#if order was set to 0 , it means deleting it
			incr dev_cmd_grp_no -1
        	} else {
        #add new record
                        log_info $info "Cannot found test $row1(1,1) and order is $order_no, Add it as new test" 6
        	        set sql_qur "INSERT INTO $TEST (id,test_name,des,type,cmd,dev,negate,sleep,round_times,belong_group,state,exit_after_cmd,order,new_conn,prev_conn,in_round,stop_test,owner,group_id) values ('','$row1(1,1)','$row1(1,2);','$row1(1,3)','$row1($order_no,4)','$row1($order_no,5)','$row1($order_no,6)','$row1($order_no,7)','$row1($order_no,8)','$row1($order_no,9)','$row1($order_no,10)','$row1($order_no,11)','$row1($order_no,12)','$row1($order_no,13)','$row1($order_no,14)','$row1($order_no,15)','$row1($order_no,16)','$operator','$group_id')"
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]
                        set k 0

                	log_info $info "$sql_qur" 6
        	        if {$infect_line == "1"} {
                	        log_info $info "Insert new test $row1(1,1) with order: $order_no into database successfully!\n" 3
        	        } else {
                	        log_info $info "Fail to insert into database !\n" 2
                        	log_info $info "$infect_line" 2
        			return 0
        	        }
        	}
	}
       	set sql_qur "DELETE FROM $TEST where test_name='$row1(1,1)' and (`order`< 1 or `order`>'$dev_cmd_grp_no') and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

       	log_info $info $sql_qur 6
       	if {$infect_line > 0} {
		log_info $info "delete $infect_line test records with bigger order number" 2
	} else {
		log_info $info "no more test record with bigger order number need be deleted" 4
	}
	return 1
}
proc attach_package_to_env {cur_env parent_line} {
        global info TREE_TB DB_NAME array1 ENV_DEV operator group_id 
#       log_info $info "parent_line: $parent_line \n" 2
#       log_info $info "array1(1,1): $array1(1,1); array1(1,2): $array1(1,2) \n" 2
        for {set i 1} {$i <= $parent_line} {incr i +1} {
                set sql_qur "INSERT INTO $TREE_TB (`name`,`parentid`,`des`,`state`,`owner`,`run_times`,`group_id`) VALUES('$array1($i,1)','$cur_env','','5','$operator',1,'$group_id')"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

                log_info $info $sql_qur 5
                if {$array1($i,2)==1} {
                        if {$infect_line == "1"} {
                                log_info $info "Insert Into database table $TREE_TB successfully!" 2
#				set run_env "$cur_env"
#				append run_env "/$array1($i,1)"
#				#Add a nouse_for_pack device is because conf_run_env will ignore run_env which does not have any \
#				device in it 
#		                set SQL_stat "INSERT INTO $ENV_DEV (`env_name`,`dev`) VALUES('$run_env','nouse_for_pack')"
#		                log_info $info $SQL_stat 5
#                        	if {[set infect_line [::mysql::exec $db_handle $SQL_stat]]=="1"} {
#                                	set log_content "Insert device nouse_for_pack into database $ENV_DEV successfully!\n"
#	                                log_info $info $log_content 2
#        	                } else {
#                	                log_info $info "Fail to insert device nouse_for_pack into database $ENV_DEV !\n" 1
#                        	        log_info $info "infect line: $infect_line \n" 1
#	                        }
                        } else {
                                log_info $info "Fail to insert into database table $TREE_TB !\n" 1
                                log_info $info "infect line: $infect_line \n" 1
                        }
                } else {}
        }
}
proc add_pack {cur_env} {
	global info TREE_TB DB_NAME array1 group_id
        set w_pack .add_new_pack
        catch {destroy $w_pack}
        toplevel $w_pack
        wm title $w_pack "Add Packages under this env"
        wm iconname $w_pack "iconname?"
        positionWindow $w_pack

	#create frame window man_win for device list
        set pack_list [ScrolledWindow $w_pack.dev -relief sunken -borderwidth 2]
        set spack_list [ScrollableFrame $w_pack.dev.f -height 500 -width 220 -constrainedwidth 1 -bg white]
        $pack_list setwidget $spack_list
        set w [$spack_list getframe]
        pack $pack_list -side top
	# get package list from tree table, where Parent_ID is 0
        set sql_qur "SELECT name from $TREE_TB where parentid='0' and group_id='$group_id' ORDER BY name "
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$parent_line > "0"} {
                log_info $info "Found $parent_line package records in DB!\n" 5
                for {set i 1} {$i <= $parent_line} {incr i +1} {
                        set array1($i,1) [lindex $sql_ret_str $k]
                        incr k +1
                        set array1($i,2) 0
                        log_info $info "array1($i,1): $array1($i,1); array1($i,2): $array1($i,2)" 6
                        checkbutton $w.$i -text $array1($i,1) -variable array1($i,2) -anchor w
                        pack $w.$i -side top -pady 2 -anchor w
                }
        } else {
                log_info $info "Cannot find any package records in DB!\n You need add package firstly" 2
                return 0
        }
        frame $w_pack.command
        button $w_pack.command.confirm -text Confirm -command " attach_package_to_env $cur_env $parent_line ; catch {destroy $w_pack} "
        button $w_pack.command.cancel -text Cancel -command " catch {destroy $w_pack} ; return 0 "
        pack $w_pack.command -side bottom  -fill x -pady 2m
        pack $w_pack.command.confirm $w_pack.command.cancel -side left -expand 1
}
proc add_env {} {
	global row1 info cur_env commit 
	set row1(2) $cur_env
	set w .edit_new_env
	catch {destroy $w}
	toplevel $w
	wm title $w "Input new environment"
	wm iconname $w "iconname?"
	positionWindow $w
	
	frame $w.left
	frame $w.right
	frame $w.command
	pack $w.left $w.right -side left -expand yes -padx 10 -pady 10 -fill both
	pack $w.command -side bottom  -fill x -pady 2m

	label $w.left.env_name -text "Env name:" -padx 0 -width 16 -anchor e  
	label $w.left.env_belong -text "Parent env:" -padx 0 -width 16 -anchor e 
	label $w.left.owner -text "Owner:" -padx 0 -width 16 -anchor e 
#	label $w.left.env_upload -text "Config file to be upload" -padx 0 -width 30 -anchor e

	entry $w.right.env_name -width 45 -relief sunken -textvariable row1(1)
	entry $w.right.env_belong -width 45 -relief sunken -textvariable row1(2) -state disable
	entry $w.right.owner -width 45 -relief sunken -textvariable operator -state disable
#	entry $w.right.env_upload -width 20 -relief sunken -textvariable row1(3)
	
	button $w.command.confirm -text Confirm -command { 
		set commit [input_env_to_db]
		}
	button $w.command.cancel -text Cancel -command { set commit 0 } 
	pack $w.command.confirm $w.command.cancel -side left -expand 1
	pack $w.left.env_name $w.left.env_belong $w.left.owner -side top -expand yes -pady 2 -anchor w
	pack $w.right.env_name $w.right.env_belong $w.right.owner -side top -expand yes -pady 2 -anchor w
	vwait commit
	catch {destroy $w}
	return commit
}
proc modi_dev {num man_win} {
	global info row1 array2 db_handle
	set row1(1) $array2($num,2)
	set row1(2) $array2($num,8)
	set row1(3) $array2($num,3)
	set row1(4) $array2($num,4)
	set row1(5) $array2($num,5)
	set row1(6) $array2($num,6)
	set row1(7) $array2($num,7)	
	set row1(8) $array2($num,9)	
	set result 2
#	log_info $info "row1(2)aaabbb: $row1(2)" 2
	set result [edit_dev]
	log_info $info "result: $result" 2
	if {$result==1} {
		log_info $info "finish to edit dev, now change display" 2
		set abc $row1(2)
#		log_info $info "row1(2): $row1(2);abc: $abc" 2
		$man_win.$num.name config -text $row1(1)
		$man_win.$num.ip config -text $row1(3)
		$man_win.$num.mode config -text $row1(4)
		$man_win.$num.user config -text $row1(5)
		$man_win.$num.pass config -text $row1(6)
		set array2($num,2) $row1(1)
		set array2($num,8) $row1(2)
		set array2($num,3) $row1(3)
		set array2($num,4) $row1(4)
		set array2($num,5) $row1(5)
		set array2($num,6) $row1(6)
		set array2($num,7) $row1(7)
		set array2($num,9) $row1(8)
	} else {
		log_info $info "Fail or cancel to edit device." 2
	}
}
proc modi_test_group_from_man {num man_win} {
        global info row_test_group array2 db_handle
        set row_test_group(1) $array2($num,2)
        set row_test_group(2) $array2($num,3)
        set row_test_group(3) $array2($num,4)
        set row_test_group(4) $array2($num,5)
        set result 2
        if {[set result [edit_env_test_group 0]]==1} {
                log_info $info "finish to edit test, now change display" 2
#                $man_win.$num.name config -text $row1(1)
#                $man_win.$num.ip config -text $row1(3)
#                $man_win.$num.mode config -text $row1(4)
#                $man_win.$num.user config -text $row1(5)
#                $man_win.$num.pass config -text $row1(6)
        } else {
                log_info $info "Fail to edit test_group. result is $result. waiting for help from forum" 2
        }
}
proc helper_modi_test {test_name} {
	global info row1 TEST db_handle DB_NAME group_id
        set sql_qur "SELECT * from $TEST where test_name='$test_name' and group_id='$group_id' ORDER BY `order`"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
        if {$parent_line >"0"} {
                log_info $info "Found $parent_line test records for test:$test_name in DB!\n" 5
                for {set i 1} {$i <= $parent_line} {incr i +1} {
                        set value_string [lindex $sql_ret_str $k]
                        incr k +1
                        set row1($i,0) [lindex $value_string 0]
                        set row1($i,1) [lindex $value_string 1]
                        set row1($i,2) [lindex $value_string 2]
                        set row1($i,3) [lindex $value_string 3]
                        set row1($i,4) [lindex $value_string 4]
                        set row1($i,5) [lindex $value_string 5]
                        set row1($i,6) [lindex $value_string 6]
                        set row1($i,7) [lindex $value_string 7]
                        set row1($i,8) [lindex $value_string 8]
                        set row1($i,9) [lindex $value_string 9]
                        set row1($i,10) [lindex $value_string 10]
                        set row1($i,11) [lindex $value_string 11]
                        set row1($i,12) [lindex $value_string 12]
                        set row1($i,13) [lindex $value_string 13]
                        set row1($i,14) [lindex $value_string 14]
                        set row1($i,15) [lindex $value_string 15]
                        set row1($i,16) [lindex $value_string 16]
                        set row1($i,17) [lindex $value_string 17]
		}
		return $parent_line
	} else {
		log_info $info "unexpected error, return from helper_modi_test" 2
		return 0
	}
}

proc modi_test_from_man {num man_win} {
        global info row1 array2 db_handle TEST
	# get test list from test table
	set name $array2($num,2)
	if {[set dev_cmd_grp_no [helper_modi_test $name]]!=0} {
	        set result 2
        	if {[set result [edit_env_test_new $dev_cmd_grp_no]]==1} {
                	log_info $info "finish to edit test, now change display" 2
	                $man_win.$num.name config -text $row1(1,1)
        	        $man_win.$num.des config -text $row1(1,2)
                	$man_win.$num.type config -text $row1(1,3)
			return 1
	        } else {
        	        log_info $info "Cancel to edit test or edit fail." 2
			return 0
	        }
	} else {
		log_info $info "error from modi_test_from_man" 2
		return 0
	}
}
proc modi_test {cur_widget} {
        global info array1 cur_env TEST db_handle array_test row1
        log_info $info "cur_widget: $cur_widget;" 6
        regexp \.f\.out_window\.oper\.test_sw\.f\.frame\.(\[0-9]*) $cur_widget unuse no
	set handle_test_name $array_test($no,1)
        log_info $info "test_name: $handle_test_name;" 6
	if {[set dev_cmd_grp_no [helper_modi_test $handle_test_name]]!=0} {
		if {[edit_env_test_new $dev_cmd_grp_no]==1} {
			log_info $info "succeed to update test $handle_test_name" 6 
			return 1
		} else {
			log_info $info "failed to update test $handle_test_name" 2
			return 0	
		}
	} else {
		log_info $info "Failed, cannot find test $handle_test_name in Env_test!" 2
		return 0
	}
}

proc del_dev {num} {
	global info row1 array2 db_handle DEV_TB DB_NAME group_id
        set sql_qur "DELETE FROM $DEV_TB WHERE name='$array2($num,2)' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]

        log_info $info "$sql_qur" 6
        if {$infect_line =="1"} {
                log_info $info "Delete $array2($num,2) from database successfully!" 3
                return 1
        } else {
                log_info $info "Fail to delete $array2($num,2) from database !" 2
                log_info $info "$infect_line" 3
                return 0
        }
}
proc man_test_group {} {
        global info row_test TEST_GROUP db_handle array2 DB_NAME group_id
        catch {destroy .man_test_group}
        catch {unset w_test_group}
        set w_test_group .man_test_group
        toplevel $w_test_group
        wm title $w_test_group "Manage test group"
        wm iconname $w_test_group "iconname?"
        positionWindow $w_test_group
        set list_group [frame $w_test_group.list]
        set comm_button [frame $w_test_group.button]
        pack $list_group -side top -fill x -pady 2m
        frame $list_group.title
        pack $list_group.title -side top
        label $list_group.title.id -text "ID" -padx 0 -width 5 -anchor e
        label $list_group.title.name -text "Group_name" -padx 0 -width 25 -anchor e
        label $list_group.title.test_list -text "Test_list" -padx 0 -width 35 -anchor e
        label $list_group.title.env_list -text "Env_list" -padx 0 -width 33 -anchor e
        label $list_group.title.des -text "Description" -padx 0 -width 25 -anchor e
        label $list_group.title.oper -text "Operation" -padx 0 -width 15 -anchor e
        pack $list_group.title.id $list_group.title.name $list_group.title.test_list $list_group.title.env_list $list_group.title.des $list_group.title.oper -side left -expand yes -pady 2 -anchor w
#create frame window man_win for device list
        set man_test_group_list [ScrolledWindow $w_test_group.dev_sw -relief sunken -borderwidth 2]
        set sman_test_group_list [ScrollableFrame $w_test_group.dev_sw.f -height 150 -width 1000 -constrainedwidth 1 -bg white]
        $man_test_group_list setwidget $sman_test_group_list
        set man_win [$sman_test_group_list getframe]
        pack $man_test_group_list -side top
# get test group list from test table
        set sql_qur "SELECT * from $TEST_GROUP and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
        if {$parent_line >"0"} {
                log_info $info "Found $parent_line test_group records in DB!\n" 5
                for {set i 1} {$i <= $parent_line} {incr i +1} {
                        frame $man_win.$i
                        pack $man_win.$i -side top
                        set value_string [lindex $sql_ret_str $k]
                        incr k +1
                        set array2($i,1) [lindex $value_string 0]
                        set array2($i,2) [lindex $value_string 1]
                        set array2($i,3) [lindex $value_string 2]
                        set array2($i,4) [lindex $value_string 3]
                        set array2($i,5) [lindex $value_string 4]

                        log_info $info $value_string 5
                        label $man_win.$i.id -text "$array2($i,1)" -padx 1 -width 5 -anchor w -bg white -relief sunken
                        label $man_win.$i.name -text "$array2($i,2)" -padx 1 -width 25 -anchor w -bg white -relief sunken
                        label $man_win.$i.des -text "$array2($i,3)" -padx 1 -width 25 -height 1 -anchor w -bg white -relief sunken
                        label $man_win.$i.test_list -text "$array2($i,4)" -padx 1 -width 35 -height 1 -anchor w -bg white -relief sunken
                        label $man_win.$i.env_list -text "$array2($i,5)" -padx 1 -width 33 -height 1 -anchor w -bg white -relief sunken
                        button $man_win.$i.edit -text "Edit" -command " modi_test_group_from_man $i $man_win"
                        button $man_win.$i.del -text "Delete" -command " del_test_group $i"
                        pack $man_win.$i.id $man_win.$i.name $man_win.$i.test_list $man_win.$i.env_list $man_win.$i.des $man_win.$i.edit $man_win.$i.del -side left -expand 1 -anchor w
                }
        } else {
                log_info $info "Cannot find any test_group records in DB! " 2
        }
        pack $comm_button -side top -fill x -pady 2m
        button $comm_button.new -text "New" -command "edit_env_test_group 1; return 1"
        button $comm_button.exit -text "Exit" -command "destroy $w_test_group; return 1"
        pack $comm_button.new -side left -pady 2 -anchor w
        pack $comm_button.exit -side left -pady 2 -anchor w
}
proc report_result {} {
        global  info commit operator run_case_no SCRIPT_DIR commit_result cur_env group_id user_id
        set w .report_test_result
        catch {destroy $w}
        toplevel $w
        wm title $w "Create test report"
        wm iconname $w "iconname?"
        positionWindow $w

        frame $w.left
        frame $w.right
        frame $w.command
        pack $w.left $w.right -side left -expand yes -padx 10 -pady 10 -fill both
        pack $w.command -side bottom  -fill x -pady 2m

        label $w.left.file_name -text "File name:" -padx 0 -width 16 -anchor e
        label $w.left.hide_env -text "Hide parent env:" -padx 0 -width 16 -anchor e
        label $w.left.owner -text "Owner:" -padx 0 -width 16 -anchor e
        label $w.left.run_case_no -text "run_case_no:" -padx 0 -width 16 -anchor e

        set file_name_entry [entry $w.right.file_name -width 45 -relief sunken ]
        set hide_env_entry [entry $w.right.hide_env -width 45 -relief sunken ]
        set owner_entry [entry $w.right.owner -width 45 -relief sunken -textvariable operator]
        set run_case_no_entry [entry $w.right.run_case_no -width 45 -relief sunken -textvariable run_case_no ]
        cd $SCRIPT_DIR
        set file_name "testcases_doc/"
        append file_name "$operator$run_case_no"
        $file_name_entry delete 0 end
        $file_name_entry insert 0 $file_name
	$hide_env_entry delete 0 end
	$hide_env_entry insert 0 $cur_env

        button $w.command.browse -text Browse -command "$file_name_entry delete 0 end; save_to_file $file_name_entry; focus $w"
        button $w.command.confirm -text Confirm -command " Create_test_report $file_name_entry $hide_env_entry $owner_entry $run_case_no_entry "
        button $w.command.cancel -text Cancel -command { set commit_result 0 }

        pack $w.command.confirm $w.command.browse $w.command.cancel -side left -expand 1
        pack $w.left.file_name $w.left.hide_env $w.left.owner $w.left.run_case_no -side top -expand yes -pady 2 -anchor w
        pack $w.right.file_name $w.right.hide_env $w.right.owner $w.right.run_case_no -side top -expand yes -pady 2 -anchor w
        vwait commit_result
        catch {destroy $w}
        return commit_result
}
proc Create_test_report {file_name_entry hide_env_entry owner_entry run_case_no_entry} {
	global SCRIPT_DIR info LOG_RESULT DB_PRV_NAME commit_result user_id
	set file_name [$file_name_entry get]
	set operator [$owner_entry get]
	set run_case_no [$run_case_no_entry get]
	set hide_env [$hide_env_entry get]
        cd $SCRIPT_DIR
        set cur_dir [eval pwd]
        if [catch {set filehandle [open $file_name w]} err_info] {
                log_info $info "Error to open file $file_name. Reason: $err_info" 2
                set commit_result 0
                return 0
        }
        log_info $info "Start to create test report for run_case_no:$operator$run_case_no" 2
	set time [clock format [clock second] -format "%b %d,%Y"]
        puts $filehandle "<br>"
        puts $filehandle "***Test result report, created by autotestnet at $time***"
        puts $filehandle "%EDITTABLE{ format = \"|textarea, 4x26 | textarea, 3x35 | textarea, 3x40| text,5 |\"}%"
        puts $filehandle "| *Test_env* | *Test_name* | *Result* | *Test_time* |"

        set list_operator "$operator$run_case_no"
        set sql_qur "SELECT test_name,result,test_env,time from $LOG_RESULT where `operator`='$list_operator' and `user_id`='$user_id' ORDER BY `time`"
        set sky_response [mysql_pack $sql_qur $DB_PRV_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
        if {$parent_line > "0"} {
                log_info $info "Found $parent_line test result records in DB!" 2
                for {set i 1} {$i <= $parent_line } {incr i +1} {
                        set value_string [lindex $sql_ret_str $k]
                        incr k +1
                        set test_name [lindex $value_string 0]
                        set test_result [lindex $value_string 1]
			if {$test_result==1} { set test_result "PASS"} else { set test_result "FAIL"}
                        set a1 [lindex $value_string 2]
                        set a2 [string length $hide_env]
                        set a3 [string range $a1 [expr $a2 +1] end]
                        log_info $info "a1:$a1 a2:$a2 a3:$a3 hide_env:$hide_env" 6
                        set test_env $a3
                        #set test_env [string range [lindex $value_string 2] [string length $hide_env] end]
                        set test_time [lindex $value_string 3]
		         puts $filehandle "|$test_env|$test_name|$test_result|$test_time|"
                }
                log_info $info "write $parent_line test result to file $file_name!" 2
	} else {
		log_info $info "no test result for $list_operator!" 2
        }
        if [catch {close $filehandle} err_info] {
                log_info $info "Error to close file. Reason: $err_info" 2
                set commit_result 0
                return 0
        }
	set commit_result 1
}
proc view_result {} {
	#Use paned window to view test result
        global info  TEST DB_PRV_NAME LOG_RESULT operator run_case_no
        catch {destroy .view_result}
        catch {unset w_viewresult}
        set w_viewresult .view_result
        toplevel $w_viewresult
        wm title $w_viewresult "View test result"
        wm iconname $w_viewresult "iconname?"
        positionWindow $w_viewresult

        set man_view_result [ScrolledWindow $w_viewresult.sw -relief sunken -borderwidth 2]
        set sman_view_result [ScrollableFrame $w_viewresult.sw.f -width 1250 -bg white]
        $man_view_result setwidget $sman_view_result
        set man_view [$sman_view_result getframe]
        pack $man_view_result -side top -expand 1

	set cmd_frame [frame $man_view.cmd]
        button $cmd_frame.tablename -text "Tablename" -command ""
        button $cmd_frame.attributes -text "Attributes" -command " "
        button $cmd_frame.refresh -text "Refresh" -command " "
        button $cmd_frame.quit -text "Quit" -command " "
	pack $cmd_frame -side top -expand yes -fill both
	pack $cmd_frame.tablename $cmd_frame.attributes $cmd_frame.refresh $cmd_frame.quit -side left -expand yes -fill both -pady 2 -padx 2m
	
#	view_table $man_view array3 $tablename $attributes
		
	set list_operator "$operator$run_case_no"
        set sql_qur "SELECT test_name,test_result,exp_result,result,test_env,time,id from $LOG_RESULT where `operator`='$list_operator' and `user_id`='$user_id' ORDER BY `time`"
        set sky_response [mysql_pack $sql_qur $DB_PRV_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
	catch {unset array3}
        set array3(1,0) "test_name"
        set array3(1,1) "test_result"
        set array3(1,2) "exp_result"
        set array3(1,3) "result"
        set array3(1,4) "test_env"
        set array3(1,5) "time"
        set array3(1,6) "id"
        if {$parent_line > "0"} {
                log_info $info "Found $parent_line device records in DB!" 4
                for {set i 2} {$i <= [expr $parent_line +1]} {incr i +1} {
                        set value_string [lindex $sql_ret_str $k]
                        incr k +1
                        set array3($i,0) [lindex $value_string 0]
                        set array3($i,1) [lindex $value_string 1]
                        set array3($i,2) [lindex $value_string 2]
                        set array3($i,3) [lindex $value_string 3]
                        set array3($i,4) [lindex $value_string 4]
                        set array3($i,5) [lindex $value_string 5]
                        set array3($i,6) [lindex $value_string 6]
                	log_info $info "array3($i,x): $array3($i,1),$array3($i,2),$array3($i,3),$array3($i,4),$array3($i,5),$array3($i,6)" 4
		}
		display_array_in_paned_window $man_view array3
	}

}
proc display_array_in_paned_window {frame_widget array_name} {
 	global info 
	upvar $array_name array3
	panedwindow $frame_widget.pane
	pack $frame_widget.pane -side top -expand yes -fill both -pady 2 -padx 2m
	set i 1
	set j 0
        log_info $info "array3($i,$j): $array3($i,0),$array3($i,1),$array3($i,2),$array3($i,3),$array3($i,4),$array3($i,5),$array3($i,6)" 4
	catch {unset frame}
	while {[info exist array3($i,$j)]} {
		set frame($j) [frame $frame_widget.pane.$j]
                log_info $info "add frame $frame_widget.pane.$j" 4
		incr j +1
	}
	set jj [expr $j -1]
	set i 1
	for {set j 0} {$j<=$jj} {incr j +1} {
		while {[info exist array3($i,$j)]} {
			label $frame($j).$i -text $array3($i,$j) -bg white -anchor w
			pack $frame($j).$i -side top -fill both -expand yes
			incr i +1
		}
		$frame_widget.pane add $frame($j) 
                log_info $info "add frame $frame_widget.pane.$j to paned window" 4
		set i 1
	}
}
proc man_test {} {
        global info row_test TEST DB_NAME array2 group_id
        catch {destroy .man_test}
        catch {unset w_test}
        set w_test .man_test
        toplevel $w_test
        wm title $w_test "Manage test"
        wm iconname $w_test "iconname?"
        positionWindow $w_test
        set list_test [frame $w_test.list]
        set comm_button [frame $w_test.button]
        pack $list_test -side top -fill x -pady 2m -expand 1
        frame $list_test.title
        pack $list_test.title -side top -expand 1
        label $list_test.title.id -text "ID" -padx 0 -width 5 -anchor e
        label $list_test.title.name -text "Test_name" -padx 0 -width 25 -anchor e
        label $list_test.title.des -text "Description" -padx 0 -width 35 -anchor e
        label $list_test.title.type -text "Type" -padx 0 -width 15 -anchor e
        label $list_test.title.order -text "Order" -padx 0 -width 5 -anchor e
#        label $list_test.title.pass -text "Command" -padx 0 -width 15 -anchor e
#        label $list_test.title.port -text "Source" -padx 0 -width 15 -anchor e
        label $list_test.title.oper -text "Operation" -padx 0 -width 15 -anchor e
#        pack $list_test.title.id $list_test.title.name $list_test.title.ip $list_test.title.mode $list_test.title.user  $list_test.title.pass $list_test.title.port $list_test.title.oper -side left -expand yes -pady 2 -anchor w
        pack $list_test.title.id $list_test.title.name $list_test.title.order $list_test.title.type $list_test.title.des $list_test.title.oper -side left -expand yes -pady 2 -anchor w -expand 1
#create frame window man_win for device list
        set man_test_list [ScrolledWindow $w_test.dev_sw -relief sunken -borderwidth 2]
        set sman_test_list [ScrollableFrame $w_test.dev_sw.f -height 150 -width 900 -constrainedwidth 1 -bg white]
        $man_test_list setwidget $sman_test_list
        set man_win [$sman_test_list getframe]
        pack $man_test_list -side top -expand 1
	# get test list from test table
        set sql_qur "SELECT id,test_name,`type`,des from $TEST where `order`=1 and group_id='$group_id' ORDER BY test_name"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
        if {$parent_line > "0"} {
                log_info $info "Found $parent_line device records in DB!\n" 5
                for {set i 1} {$i <= $parent_line} {incr i +1} {
                        frame $man_win.$i
                        pack $man_win.$i -side top
                        set value_string [lindex $sql_ret_str $k]
                        incr k +1
                        set array2($i,1) [lindex $value_string 0]
                        set array2($i,2) [lindex $value_string 1]
                        set array2($i,3) [lindex $value_string 2]
                        set array2($i,4) [lindex $value_string 3]

                        label $man_win.$i.id -text "$array2($i,1)" -padx 1 -width 5 -anchor w -bg white -relief sunken
                        label $man_win.$i.name -text "$array2($i,2)" -padx 1 -width 25 -anchor w -bg white -relief sunken
                        label $man_win.$i.type -text "$array2($i,3)" -padx 1 -width 35 -height 1 -anchor w -bg white -relief sunken
                        label $man_win.$i.des -text "$array2($i,4)" -padx 1 -width 45 -height 1 -anchor w -bg white -relief sunken
                        button $man_win.$i.edit -text "Edit" -command " modi_test_from_man $i $man_win"
                        button $man_win.$i.del -text "Delete" -command " del_test $i"
                        pack $man_win.$i.id $man_win.$i.name $man_win.$i.type $man_win.$i.des $man_win.$i.edit $man_win.$i.del -side left -expand 1 -anchor w
                }
        } else {
                log_info $info "Cannot find any device records in DB! " 2
        }
        pack $comm_button -side top -fill x -pady 2m
        button $comm_button.new -text "New" -command "edit_env_test_new 0; return 1"
        button $comm_button.exit -text "Exit" -command "destroy $w_test; return 1"
        pack $comm_button.new -side left -pady 2 -anchor w
        pack $comm_button.exit -side left -pady 2 -anchor w
}

proc man_dev {} {
	global info row1 DEV_TB DB_PRV_NAME DB_NAME array2 user_id
	catch {destroy .man_dev}
	catch {unset w1}
	set w1 .man_dev
	toplevel $w1
	wm title $w1 "Manage device"
	wm iconname $w1 "iconname?"
	positionWindow $w1
	set list_dev [frame $w1.list]
	set comm_button [frame $w1.button]
	pack $list_dev -side top -fill x -pady 2m
	frame $list_dev.title
	pack $list_dev.title -side top
	label $list_dev.title.id -text "ID" -padx 2 -width 5 -anchor center
	label $list_dev.title.name -text "Name" -padx 2 -width 20 -anchor center
	label $list_dev.title.ip -text "IP_address" -padx 2 -width 20 -anchor center
	label $list_dev.title.mode -text "Mode" -padx 2 -width 10 -anchor center
	label $list_dev.title.user -text "User" -padx 2 -width 15 -anchor center
	label $list_dev.title.pass -text "Password" -padx 2 -width 15 -anchor center
	label $list_dev.title.port -text "Access Port" -padx 2 -width 15 -anchor center
	label $list_dev.title.oper -text "Operation" -padx 2 -width 20 -anchor center
	pack $list_dev.title.id $list_dev.title.name $list_dev.title.ip $list_dev.title.mode $list_dev.title.user  $list_dev.title.pass $list_dev.title.port $list_dev.title.oper -side left -expand yes -pady 2 -anchor w
#create frame window man_win for device list
	set man_dev_list [ScrolledWindow $w1.dev_sw -relief sunken -borderwidth 2]
	set sman_dev_list [ScrollableFrame $w1.dev_sw.f -height 150 -width 900 -constrainedwidth 1 -bg white]
	$man_dev_list setwidget $sman_dev_list
	set man_win [$sman_dev_list getframe]
	pack $man_dev_list -side top

# get device list from dev_access table
        set sql_qur "SELECT * from $DEV_TB where user_id='$user_id' ORDER BY name"
        set sky_response [mysql_pack $sql_qur $DB_PRV_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0


        log_info $info "$sql_qur" 6
        if {$parent_line > "0"} {
                log_info $info "Found $parent_line device records in DB!\n" 5
                for {set i 1} {$i <= $parent_line} {incr i +1} {
			frame $man_win.$i
			pack $man_win.$i -side top
			set value_string [lindex $sql_ret_str $k]
                        incr k +1
			set array2($i,1) [lindex $value_string 0]
			set array2($i,2) [lindex $value_string 1]
			set array2($i,3) [lindex $value_string 3]
			set array2($i,4) [lindex $value_string 4]
			set array2($i,5) [lindex $value_string 5]
			set array2($i,6) [lindex $value_string 6]
			set array2($i,7) [lindex $value_string 7]
			set array2($i,8) [lindex $value_string 2]
			set array2($i,9) [lindex $value_string 8]
			log_info $info $value_string 5
			label $man_win.$i.id -text "$array2($i,1)" -padx 2 -width 5 -anchor e -relief sunken
			label $man_win.$i.name -text "$array2($i,2)" -padx 2 -width 22 -anchor e -relief sunken
			label $man_win.$i.ip -text "$array2($i,3)" -padx 2 -width 22 -anchor e -relief sunken
			label $man_win.$i.mode -text "$array2($i,4)" -padx 2 -width 10 -anchor e -relief sunken
			label $man_win.$i.user -text "$array2($i,5)" -padx 2 -width 15 -anchor e -relief sunken
			label $man_win.$i.pass -text "$array2($i,6)" -padx 2 -width 15 -anchor e -relief sunken
			label $man_win.$i.port -text "$array2($i,7)" -padx 2 -width 15 -anchor e -relief sunken
			button $man_win.$i.edit -text "Edit" -command " modi_dev $i $man_win" 
			button $man_win.$i.del -text "Delete" -command " del_dev $i"
        		pack $man_win.$i.id $man_win.$i.name $man_win.$i.ip $man_win.$i.mode $man_win.$i.user $man_win.$i.pass $man_win.$i.port $man_win.$i.edit $man_win.$i.del -side left -expand 1 -anchor w
		}
        } else {
                log_info $info "Cannot find any device records in DB!\n " 2
        }
        pack $comm_button -side top -fill x -pady 2m
        button $comm_button.new -text "New" -command {set row1(4) "telnet"; set row1(7) 23; set row1(8) "FortiOS"; edit_dev; return 1}
        button $comm_button.exit -text "Exit" -command "destroy $w1; return 1"
        pack $comm_button.new -side left -pady 2 -anchor w
        pack $comm_button.exit -side left -pady 2 -anchor w
}
proc edit_dev {} {
	global info row1 commit
	upvar row1 row1
	set w .edit_new_dev
	catch {destroy $w}
	toplevel $w
	wm title $w "Input/modify test device"
	wm iconname $w "iconname?"
	positionWindow $w
	
	frame $w.left
	frame $w.right
	frame $w.command
	pack $w.left $w.right -side left -expand yes -padx 10 -pady 10 -fill both
	pack $w.command -side bottom  -fill x -pady 2m

	label $w.left.dev_name -text "Device name" -padx 0 -width 15 -anchor e  
	
	label $w.left.dev_des -text "Description" -padx 0 -width 15 -anchor e 
	label $w.left.dev_ip -text "IP address" -padx 0 -width 15 -anchor e
	label $w.left.dev_mode -text "Access mode" -padx 0 -width 15 -anchor e
	label $w.left.dev_user -text "Access user" -padx 0 -width 15 -anchor e
	label $w.left.dev_pass -text "Access password" -padx 0 -width 15 -anchor e
	label $w.left.dev_port -text "Access port" -padx 0 -width 15 -anchor e
	label $w.left.dev_type -text "OS type" -padx 0 -width 15 -anchor e
	

	entry $w.right.dev_name -width 20 -relief sunken -textvariable row1(1)
	entry $w.right.dev_ip -width 20 -relief sunken -textvariable row1(3)
	set telnet_value "telnet"
	ComboBox $w.right.dev_mode -values {"telnet" "ssh" "minicom"} -text "$row1(4)" -helptext "select access mode" -textvariable row1(4) -modifycmd { 
	if {$row1(4)=="telnet"} {
		set row1(7) 23
	} else {
		set row1(7) 22
	}}
	entry $w.right.dev_user -width 20 -relief sunken -textvariable row1(5)
	entry $w.right.dev_pass -validate key -show "*" -vcmd {expr {[string length %P]<=16}} -width 20 -relief sunken -textvariable row1(6)
	entry $w.right.dev_port -width 20 -relief sunken -textvariable row1(7)
	entry $w.right.dev_des  -width 50 -relief sunken -textvariable row1(2)
        ComboBox $w.right.dev_type -values {"IOS" "CatOS" "FortiOS" "Linux" "WinOS" "Others"} -text "$row1(8)" -helptext "select OS type" -textvariable row1(8)
	
	button $w.command.confirm -text Confirm -command { 
		set commit [input_dev_to_db] }
	button $w.command.cancel -text Cancel -command { set commit 0 }
	pack $w.command.confirm $w.command.cancel -side left -expand 1
	pack $w.left.dev_name $w.left.dev_ip $w.left.dev_mode $w.left.dev_user $w.left.dev_pass $w.left.dev_port $w.left.dev_type $w.left.dev_des -side top -expand yes -pady 2 -anchor w
	pack $w.right.dev_name $w.right.dev_ip $w.right.dev_mode $w.right.dev_user $w.right.dev_pass $w.right.dev_port $w.right.dev_type $w.right.dev_des -side top -expand yes -pady 2 -anchor w
	vwait commit
	catch {destroy $w} ;
	return $commit
}

proc sele_test {entry_widget} {
	global info array_test  row_test_group
	set i 1
	while {[info exists array_test($i,1)]} {
		if {$array_test($i,2)==1} {
			if {[string first "$array_test($i,1);" $row_test_group(3)]==-1} {
				set row_test_group(3) [append row_test_group(3) "$array_test($i,1);"]
			} else {
				log_info $info "$row_test_group(1) test_group already include $array_test($i,1), don't need add it again" 2
			}
		}
		incr i +1
	}	
	$entry_widget config -textvariable row_test_group(3)
}
proc edit_env_test_group {new} {
	global info cur_env row_test_group ENV_DEV TEST_GROUP db_handle commit1 array_test
#new=1 means creating a new test
	if {$new==1} {
		for {set i 1} {$i<=4} {incr i +1} {
			set row_test_group($i) ""
		}
	}
	
	set w .edit_test_group
	catch {destroy $w}
	toplevel $w
	wm title $w "Input new test_group item"
	wm iconname $w "iconname?"
	positionWindow $w
	set test_group_name [frame $w.test_name]
	set des [frame $w.des]
	set test_list [frame $w.test_list]
	set env_list [frame $w.env_list]
	pack $test_group_name $test_list $env_list $des -side top -fill x -pady 2m
	frame $w.command
	pack $w.command -side bottom  -fill x -pady 2m

	label $test_group_name.label -text "test_group_name" -padx 0 -width 15 -anchor e  
        entry $test_group_name.entry -width 20 -relief sunken -textvariable row_test_group(1) -bg white
	pack $test_group_name.label $test_group_name.entry -side left -pady 2 -anchor w

	label $test_list.label -text "Test list" -padx 0 -width 15 -anchor e 
	entry $test_list.entry -width 20 -relief sunken -textvariable row_test_group(3) -bg white -state disable
	button $test_list.browser -text Browse -command "
		add_env_test_aux $test_list.entry;
		sele_test $test_list.entry; "
	pack $test_list.label $test_list.entry $test_list.browser -side left -pady 2 -anchor w
	label $env_list.label -text "Env list" -padx 0 -width 15 -anchor e 
	entry $env_list.entry -width 20 -relief sunken -textvariable row_test_group(4) -bg white -state disable
	pack $env_list.label $env_list.entry -side left -pady 2 -anchor w 
	label $des.label -text "Description" -padx 0 -width 15 -anchor e 
	entry $des.entry -width 50 -relief sunken -textvariable row_test_group(2) -bg white 
	pack $des.label $des.entry -side left -pady 2 -anchor w
	
	button $w.command.confirm -text Confirm -command {set commit1 [input_test_group_to_db] }
	button $w.command.cancel -text Cancel -command {set commit1 0 }
	pack $w.command.confirm $w.command.cancel -side left -expand 1
	vwait commit1
	catch {destroy $w}
	return $commit1
}
proc add_env_test_aux {widget} {
	set old_test_list [$widget get]
	add_env_test 0 $old_test_list
}
proc get_dev_list_in_env {env} {
	global info DB_NAME ENV_DEV group_id
        set sql_qur "SELECT dev from $ENV_DEV where env_name like '%$env%' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
        set dev_list ""
        if {$parent_line > "0"} {
                log_info $info "Found $parent_line device records in DB!" 5
                for {set i 1} {$i <= $parent_line} {incr i +1} {
                        set dev_name [lindex $sql_ret_str $k]
                        incr k +1
			if {[string first $dev_name $dev_list]==-1} {
	                        append dev_list $dev_name
        	                append dev_list " "
                	        log_info $info "dev_list: $dev_list " 6
			}
                }
        }
	return $dev_list
}
proc get_dev_list_in_db {} {
        global info DB_PRV_NAME DEV_TB user_id
        set sql_qur "SELECT name from $DEV_TB where user_id='$user_id' ORDER BY name"
        set sky_response [mysql_pack $sql_qur $DB_PRV_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
        set dev_list ""
        if {$parent_line >"0"} {
                log_info $info "Found $parent_line device records in DB!" 5
                for {set i 1} {$i <= $parent_line} {incr i +1} {
                        set dev_name [lindex $sql_ret_str $k]
                        incr k +1
                        append dev_list $dev_name
                        append dev_list " "
                        log_info $info "dev_list: $dev_list " 6
                }
        }
        return $dev_list
}

proc edit_env_test {new} {
	global info cur_env row1 ENV_DEV db_handle commit
#new=1 means creating a new test
	set row1(2) ""
	if {$new==1} {
		for {set i 1} {$i<=17} {incr i +1} {
			set row1($i) ""
		}
		set row1(2) $cur_env
		set row1(4) "check"
                set row1(16) "3"
                set row1(17) "1"
	}
	if {[string trim $row1(8)]!=""} {
		set row1(5) [string trim $row1(5)]
		append row1(5) "|||"
		append row1(5) "$row1(8)"
		set row1(8) ""
	}
#	set test_type {ping check r_check h323_ohphone}
	set test_type {check r_check }
#set dev_list
	set dev_list [get_dev_list_in_db]
	
	set w .edit_env_test
	catch {destroy $w}
	toplevel $w
	wm title $w "Input new test item"
	wm iconname $w "iconname?"
	positionWindow $w
	set test_name [frame $w.test_name]
	set des [frame $w.des]
	set env_name [frame $w.env_name]
	set type [frame $w.type]
	set cmd [frame $w.cmd]
	set src [frame $w.src]
	set exp_res [frame $w.exp_res]
	set pre_src [frame $w.pre_src]
	set pre_cmd [frame $w.pre_cmd]
	set post_src [frame $w.post_src]
	set post_cmd [frame $w.post_cmd]
	set sleep [frame $w.sleep]
	set round [frame $w.round]
	set group [frame $w.group]
	set state [frame $w.state]
	set exit_after_pre_cmd [frame $w.exit]
	pack $test_name $type $pre_src $pre_cmd $sleep $src $cmd $post_src $post_cmd $round $group $state $exit_after_pre_cmd $des -side top -fill x -pady 1 -expand 1
	frame $w.command
	pack $w.command -side bottom  -fill x -pady 2m

	label $test_name.label -text "test_name" -padx 0  -width 15 -anchor e  
        entry $test_name.entry -width 50 -relief sunken -textvariable row1(1) -bg white
	pack $test_name.label $test_name.entry -side left -pady 1 -anchor w

	label $des.label -text "Description" -padx 0 -width 15 -anchor e 
	set des_txt [text $des.entry -yscrollcommand "$des.sb set" -height 4 -width 60]
	scrollbar $des.sb -orient vertical -command "$des_txt yview"
        $des_txt insert end $row1(3)
	pack $des.label $des.entry -side left  -pady 1 -anchor w -expand 1
	pack $des.sb -side left -fill y

	label $type.label -text "Test Type" -padx 0 -width 15 -anchor e
	ComboBox $type.entry -values $test_type -text "$row1(4)" -width 18 -relief sunken -textvariable row1(4) -modifycmd {
	        if {$row1(4)=="h323_ohphone"} {
		        pack .edit_env_test.src.dst_label .edit_env_test.src.dst_entry -side left -pady 2 -anchor w
	        } else {
        	        pack forget .edit_env_test.src.dst_label .edit_env_test.src.dst_entry 
		}} 
	
	pack $type.label $type.entry -side left -pady 1 -anchor w 
	label $cmd.label -text "Command" -padx 0 -width 15 -anchor e
        set cmd_txt [text $cmd.entry -yscrollcommand "$cmd.sb set" -height 4 -width 60]
        scrollbar $cmd.sb -orient vertical -command "$cmd_txt yview"
        $cmd_txt insert end $row1(5)

	label $src.label -text "Source" -padx 0 -width 15 -anchor e
	ComboBox $src.entry -values $dev_list -text "$row1(6)" -width 15 -relief sunken -textvariable row1(6) 
	checkbutton $src.neg -text "Negate_test" -variable row1(20) -anchor w

        label $src.dst_label -text "Destination" -padx 0 -width 15 -anchor e
        ComboBox $src.dst_entry -values $dev_list -text "$row1(7)" -width 15 -relief sunken -textvariable row1(7)
#        pack $src.dst_label $src.dst_entry -side right -pady 2 -anchor w
#	label $exp_res.label -text "Expect Result" -padx 0 -width 15 -anchor e
#	entry $exp_res.entry  -width 50 -relief sunken -textvariable row1(8) -bg white
#	pack $exp_res.label $exp_res.entry -side left -pady 1 -anchor w
	label $pre_src.label -text "Pre Source" -padx 0 -width 15 -anchor e
	ComboBox $pre_src.entry -values $dev_list -text "$row1(9)" -width 15 -relief sunken -textvariable row1(9) 
	checkbutton $pre_src.neg -text "Negate_pre_test" -variable row1(19) -anchor w
	label $pre_cmd.label -text "Pre Command" -padx 0 -width 15 -anchor e
        set pre_cmd_txt [text $pre_cmd.entry -yscrollcommand "$pre_cmd.sb set" -height 4 -width 60]
        scrollbar $pre_cmd.sb -orient vertical -command "$pre_cmd_txt yview"
        $pre_cmd_txt insert end $row1(10)

        label $post_src.label -text "Post Source" -padx 0 -width 15 -anchor e
        ComboBox $post_src.entry -values $dev_list -text "$row1(11)" -width 15 -relief sunken -textvariable row1(11)
	checkbutton $post_src.neg -text "Negate_post_test" -variable row1(21) -anchor w

        label $post_cmd.label -text "Post Command" -padx 0 -width 15 -anchor e
        set post_cmd_txt [text $post_cmd.entry -yscrollcommand "$post_cmd.sb set" -height 4 -width 60 ]
        scrollbar $post_cmd.sb -orient vertical -command "$post_cmd_txt yview"
        $post_cmd_txt insert end $row1(12)

	label $sleep.label -text "Sleep time" -padx 0 -width 15 -anchor e
	entry $sleep.entry -width 20 -relief sunken -textvariable row1(13) -bg white
	label $round.label -text "Round times" -padx 0 -width 15 -anchor e
	entry $round.entry -width 20 -relief sunken -textvariable row1(14) -bg white
#	pack $round.label $round.entry -side left -pady 1 -anchor w
	label $group.label -text "Belonged Group" -padx 0 -width 15 -anchor e
	entry $group.entry -width 50 -relief sunken -textvariable row1(15) -bg white
#	pack $group.label $group.entry -side left -pady 1 -anchor w
	label $state.label -text "State" -padx 0 -width 15 -anchor e
	entry $state.entry -width 1 -relief sunken -textvariable row1(16) -bg white
	pack $state.label $state.entry -side left -pady 1 -anchor w
	label $exit_after_pre_cmd.label -text "Others" -padx 0 -width 15 -anchor e
	checkbutton $exit_after_pre_cmd.pre_cmd -text "Exit_pre_cmd" -variable row1(17) 
	checkbutton $exit_after_pre_cmd.cmd -text "Exit_cmd" -variable row1(18) 
	checkbutton $exit_after_pre_cmd.newconn -text "New connection for same device" -variable row1(22) 
	pack $exit_after_pre_cmd.label $exit_after_pre_cmd.pre_cmd $exit_after_pre_cmd.cmd $exit_after_pre_cmd.newconn -side left -pady 1 -anchor w
	
	button $w.command.confirm -text Confirm -command "
		input_test_to_db $des_txt $cmd_txt $pre_cmd_txt $post_cmd_txt;
		set commit 1 "
	button $w.command.cancel -text Cancel -command {set commit 0 }
	button $w.command.help -text Help -command "help_edit_test $w"

	pack $pre_src.label $pre_src.entry $pre_src.neg -side left -pady 1 -anchor w
        pack $pre_cmd.label $pre_cmd.entry -side left  -pady 1 -anchor w -expand 1
        pack $pre_cmd.sb -side left -fill y

	pack $sleep.label $sleep.entry -side left -pady 1 -anchor w
	
	pack $src.label $src.entry $src.neg -side left -pady 1 -anchor w
        pack $cmd.label $cmd.entry -side left  -pady 1 -anchor w
        pack $cmd.sb -side left -fill y

        pack $post_src.label $post_src.entry $post_src.neg -side left -pady 1 -anchor w
        pack $post_cmd.label $post_cmd.entry -side left  -pady 1 -anchor w -expand 1
        pack $post_cmd.sb -side left -fill y 

	pack $w.command.confirm $w.command.cancel $w.command.help -side left -expand 1
	vwait commit
	catch {destroy $w}
	return $commit

}

proc edit_env_test_new {new} {
	global info cur_env row1 ENV_DEV db_handle commit cmd_txt_widget_list dev_cmd_index dev_cmd_grp_no 
	#new=0 means creating a new test, otherwise it means dev_cmd_grp_no
	set cmd_txt_widget_list {}
	if {$new==0} {
		set dev_cmd_grp_no 2
		set row1(1,4) "###input test command here"
		set row1(1,2) "###input description/comments here"
		set row1(1,3) "check"
#		for {set j 1} {$j<=$dev_cmd_grp_no} {incr j +1} {
#			for {set i 1} {$i<=16} {incr i +1} {
#				set row1($j,$i) ""
#			}
#		}
	} else {
		set dev_cmd_grp_no $new
	}
	#	set test_type {ping check r_check h323_ohphone}
	set test_type {check r_check }
	
	set w .edit_env_test
	catch {destroy $w}
	toplevel $w
	wm title $w "Input new test item"
	wm iconname $w "iconname?"
	positionWindow $w
	set test_name [frame $w.test_name]
	set description [frame $w.des]
	set env_name [frame $w.env_name]
	set type [frame $w.type]
	set round [frame $w.round]
	set command [frame $w.command]

	pack $test_name $env_name $type -side top -fill x -expand 0 

	set sw_dev_cmd_list [ScrolledWindow $w.dev_cmd_list -relief sunken -borderwidth 2]
	#set sff_dev_cmd_list [ScrollableFrame $w.dev_cmd_list.f -constrainedwidth 1 -areaheight 0]
	set sff_dev_cmd_list [ScrollableFrame $w.dev_cmd_list.f -constrainedwidth 1 -height 350 ]
	$sw_dev_cmd_list setwidget $sff_dev_cmd_list
	set sf_dev_cmd_list [$sff_dev_cmd_list getframe]
	pack $sw_dev_cmd_list -side top -fill both -expand 1

	set add_drop_cmd [frame $sf_dev_cmd_list.add_drop_cmd -relief sunken -borderwidth 2]
	pack $add_drop_cmd -side bottom -fill both -expand 1 -pady 2
	log_info $info "dev_cmd_grp_no: $dev_cmd_grp_no" 4
	log_info $info "cmd_txt_widget_list: $cmd_txt_widget_list" 5
	button $add_drop_cmd.add -text "Add device" -command [list helper_add_dev_cmd_grp $sf_dev_cmd_list  cmd_txt_widget_list]
	button $add_drop_cmd.drop -text "Drop device" -command [list helper_drop_dev_cmd_grp $sf_dev_cmd_list  cmd_txt_widget_list]
	pack $add_drop_cmd.add $add_drop_cmd.drop -side left -expand 1

	pack $round -side top -fill x -expand 0
	pack $description -side top -fill x -expand 0
	pack $command -side bottom  -fill x -pady 2m -expand 0


	label $test_name.label -text "test_name" -padx 0  -width 10 -anchor e  
        entry $test_name.entry -width 50 -relief sunken -textvariable row1(1,1) -bg white
	pack $test_name.label $test_name.entry -side left -pady 1 -anchor w

	label $type.label -text "Test Type" -padx 0 -width 10 -anchor e
	ComboBox $type.entry -values $test_type -text "$row1(1,3)" -width 18 -relief sunken -textvariable row1(1,3) -modifycmd {
	        if {$row1(1,3)=="h323_ohphone"} {
		        pack .edit_env_test.src.dst_label .edit_env_test.src.dst_entry -side left -pady 2 -anchor w
	        } else {
        	        pack forget .edit_env_test.src.dst_label .edit_env_test.src.dst_entry 
		}} 
	pack $type.label $type.entry -side left -pady 1 -anchor w -fill x

	label $round.label -text "Round times" -padx 0 -width 10 -anchor e
	entry $round.entry -width 20 -relief sunken -textvariable row1(1,8) -bg white
	label $round.state_label -text "State" -padx 0 -width 10 -anchor e
	entry $round.state_entry -width 1 -relief sunken -textvariable row1(1,10) -bg white
	pack $round.label $round.entry $round.state_label $round.state_entry -side left -pady 1 -anchor w 

	label $description.label -text "Description" -padx 0 -width 10 -anchor e 
	set des_txt [text $description.entry -yscrollcommand "$description.sb set" -height 6]
	#set des_txt [text $description.entry -yscrollcommand "$description.sb set" -height 4 -width 85]
	scrollbar $description.sb -orient vertical -command "$des_txt yview"
        $des_txt insert end $row1(1,2)
	pack $description.label -side left  -pady 1 -anchor w
	pack $description.entry -side left  -pady 1 -anchor w -expand 1 -fill both
	pack $description.sb -side top -expand 1 -fill y


	for {set dev_cmd_index 1} {$dev_cmd_index<=$dev_cmd_grp_no} {incr dev_cmd_index +1} {
		add_dev_cmd_grp $dev_cmd_index $sf_dev_cmd_list cmd_txt_widget_list
	}	
	button $command.confirm -text Confirm -command " 
		log_info $info \"list: $cmd_txt_widget_list\" 5;
		input_test_to_db $des_txt cmd_txt_widget_list;
		set commit 1 "
	button $command.cancel -text Cancel -command {set commit 0 }
	button $command.help -text Help -command "help_edit_test $w"
	pack $command.confirm $command.cancel $command.help -side left -expand 1

	vwait commit
	catch {destroy $w}
	return $commit

}
proc add_dev_cmd_grp {dev_cmd_index parent_widget cmd_txt_list_widget} {	
	global info row1 stop_test_value 
	upvar $cmd_txt_list_widget cmd_txt_widget_list
	set row1($dev_cmd_index,12) $dev_cmd_index
	#set dev_list
	set dev_list [get_dev_list_in_db]
	if {![info exists row1($dev_cmd_index,3)]} {set row1($dev_cmd_index,3) "check"}
	if {![info exists row1($dev_cmd_index,4)]} {set row1($dev_cmd_index,4) ""}
	if {![info exists row1($dev_cmd_index,6)]} {set row1($dev_cmd_index,6) "0"}
	if {![info exists row1($dev_cmd_index,7)]} {set row1($dev_cmd_index,7) "0"}
	if {![info exists row1($dev_cmd_index,8)]} {set row1($dev_cmd_index,8) "1"}
	if {![info exists row1($dev_cmd_index,10)]} {set row1($dev_cmd_index,10) "3"}
	if {![info exists row1($dev_cmd_index,11)]} {set row1($dev_cmd_index,11) "1"}
	if {![info exists row1($dev_cmd_index,13)]} {set row1($dev_cmd_index,13) "1"}
	if {![info exists row1($dev_cmd_index,14)]} {set row1($dev_cmd_index,14) "0"}
	if {![info exists row1($dev_cmd_index,15)]} {set row1($dev_cmd_index,15) "1"}
	if {![info exists row1($dev_cmd_index,16)]} {set row1($dev_cmd_index,16) "1"}
		set frame_widget($dev_cmd_index) [frame $parent_widget.$dev_cmd_index -relief sunken -borderwidth 2]
		pack $frame_widget($dev_cmd_index) -side top -fill both -expand 1 -pady 2
		set cmd [frame $frame_widget($dev_cmd_index).cmd]
		set dev [frame $frame_widget($dev_cmd_index).dev]
		set sleep [frame $frame_widget($dev_cmd_index).sleep]
		set group [frame $frame_widget($dev_cmd_index).group]
		set others [frame $frame_widget($dev_cmd_index).exit]
		pack $dev -side top -fill x 
		pack $cmd -side top -fill x -pady 1 -expand 1
		pack $sleep $group $others -side top -fill x 

		label $dev.label -text "Device" -padx 0 -width 10 -anchor e
		ComboBox $dev.entry -values $dev_list -width 15 -relief sunken -textvariable row1($dev_cmd_index,5) 
		label $dev.order -text "Order:" -padx 0 -width 8 -anchor e
		entry $dev.order_entry -width 2 -relief sunken -textvariable row1($dev_cmd_index,12) -bg white
		checkbutton $dev.neg -text "Negate_test" -variable row1($dev_cmd_index,6) -anchor w
		set stop_test_type {"1:stop immediately" "2:finish current round then stop" "3:do following test" }
	        label $dev.stop_test -text "If fail" -padx 0 -width 10 -anchor e
		if {$row1($dev_cmd_index,16)=="3"} {
			set stop_test_value($dev_cmd_index) "3:do following test"
		} elseif {$row1($dev_cmd_index,16)=="2"} {
			set stop_test_value($dev_cmd_index) "2:finish current round then stop"
		} else {
			log_info $info "row1($dev_cmd_index,16): $row1($dev_cmd_index,16)" 5
			set stop_test_value($dev_cmd_index) "1:stop immediately"
		}
		log_info $info "row1($dev_cmd_index,16): $row1($dev_cmd_index,16); stop_test_value($dev_cmd_index): $stop_test_value($dev_cmd_index)" 6
	        ComboBox $dev.stop_test_value -values $stop_test_type -text "$stop_test_value($dev_cmd_index)" -width 30 -relief sunken -textvariable stop_test_value($dev_cmd_index) -modifycmd [list helper_stop_test $dev_cmd_index ]
		pack $dev.label $dev.entry $dev.order $dev.order_entry $dev.neg $dev.stop_test $dev.stop_test_value -side left -pady 1 -anchor w 

		label $cmd.label -text "Command$dev_cmd_index" -padx 0 -width 10 -anchor e
	        set cmd_txt [text $cmd.entry -yscrollcommand "$cmd.sb set" -height 6 -width 80 ]
	        scrollbar $cmd.sb -orient vertical -command "$cmd_txt yview"
        	$cmd_txt insert end $row1($dev_cmd_index,4)
	        pack $cmd.label -side left  -pady 1 -anchor w  -fill x
	        pack $cmd.entry -side left  -pady 1 -anchor w -expand 1 -fill both
        	pack $cmd.sb -side left -fill y

		lappend cmd_txt_widget_list $cmd_txt

		label $sleep.label -text "Sleep time" -padx 0 -width 10 -anchor e
		entry $sleep.entry -width 20 -relief sunken -textvariable row1($dev_cmd_index,7) -bg white
		pack $sleep.label $sleep.entry -side left -pady 1 -anchor w
		label $group.label -text "Belonged Group" -padx 0 -width 10 -anchor e
		entry $group.entry -width 50 -relief sunken -textvariable row1($dev_cmd_index,9) -bg white
		#	pack $group.label $group.entry -side left -pady 1 -anchor w
		label $others.label -text "Others" -padx 0 -width 9 -anchor e
		checkbutton $others.exit_cmd -text "Exit after cmd" -variable row1($dev_cmd_index,11) 
		label $others.prev_conn_label -text "Prev connection" -padx 0 -width 15 -anchor e 
		entry $others.prev_conn_entry -width 2 -relief sunken -textvariable row1($dev_cmd_index,14) 
		checkbutton $others.newconn -text "New connection" -variable row1($dev_cmd_index,13) -command [list helper_newconn $dev_cmd_index $others]
		checkbutton $others.inround -text "In round" -variable row1($dev_cmd_index,15) 
		pack $others.label $others.exit_cmd $others.newconn $others.inround $others.prev_conn_label $others.prev_conn_entry -side left -pady 1 -anchor w
}

proc helper_add_dev_cmd_grp {sf_dev_cmd_list cmd_txt_list_widget} {
	global info row1 dev_cmd_grp_no
	upvar $cmd_txt_list_widget cmd_txt_widget_list 
	log_info $info "dev_cmd_grp_no: $dev_cmd_grp_no" 4
	log_info $info "cmd_txt_widget_list: $cmd_txt_widget_list" 5

	incr dev_cmd_grp_no +1
	add_dev_cmd_grp $dev_cmd_grp_no $sf_dev_cmd_list cmd_txt_widget_list
}
proc helper_drop_dev_cmd_grp {sf_dev_cmd_list cmd_txt_list_widget} {
	global info row1 dev_cmd_grp_no
	upvar $cmd_txt_list_widget cmd_txt_widget_list 
	pack forget $sf_dev_cmd_list.$dev_cmd_grp_no
	incr dev_cmd_grp_no -1
	set cmd_txt_list_widget [lreplace $cmd_txt_widget_list end end]
}
proc helper_stop_test {dev_cmd_index } {
	global row1 info stop_test_value
        if {$stop_test_value($dev_cmd_index)=="3:do following test"} {
                set row1($dev_cmd_index,16) "3"
        } elseif {$stop_test_value($dev_cmd_index)=="2:finish current round then stop"} {
                set row1($dev_cmd_index,16) "2"
        } else {
                set row1($dev_cmd_index,16) "1"
        }
}
proc helper_newconn {dev_cmd_index base} {
	global info row1
	log_info $info "i:$dev_cmd_index; $row1($dev_cmd_index,13)" 2
	if {$row1($dev_cmd_index,13)==0} {
		$base.prev_conn_entry configure -state normal
	} else {
		$base.prev_conn_entry configure -state disabled
	}
} 


proc help_edit_test {w} {
	option add *Dialog.msg.font {Times 12}
	option add *Dialog.msg.wrapLength 6i userDefault
        tk_messageBox -icon info -type ok -title "About Test Item " -parent $w -message \
".Test order will follow the order of list

.For test command, you can add \'expect_string\' after command by \'\|\|\|\' directly. for example:
exec ping 192.168.6.222 |||reply from 192.168.6.222
exec ping 192.168.6.222 |||reply from 192.168.6.223
.For each command line, after sending command part, it will expect the \"expect_string\" when there is expect_string, and then it will expect prompt(for the last line of each command group, do not expect prompt).
.You can change prompt string manually by \"prompt_test \{prompt_string\}\"
.In each test, if test does not get any one expect text and no negate checked, program will stop to run left commands and left tests

.Negate box means you hope to not get the expect result, if you get it, that means test failed
.You can add 'sleep_test number' command to make program sleep for some seconds. for example:
sleep_test 10
.You can add some comments by '###'. For example:
###below command is using for my special test 
"
}
proc assign_test_to_env {test env group} {
	global info ENV_TEST DB_NAME group_id
	if {[string trim $test]==""} {
		log_info $info "Should not add a NULL test to env:$env, exit" 2
		return 0
	}
        set sql_qur "SELECT * from $ENV_TEST WHERE test_name='$test' and env_name='$env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$parent_line =="0"} {
                log_info $info " Add test: $test to env: $env" 2
		set sql_qur "INSERT INTO $ENV_TEST (`env_name`,`test_name`,`test_group`,`exp_result`,`description`,`state`,`group_id`) VALUES('$env','$test','$group','0','','1','$group_id')"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set infect_line [lindex $sky_response 0]

		if {$infect_line =="1"} {
			log_info $info "Insert Into database $ENV_TEST successfully!" 2
			return 1
		} else {
			log_info $info "Fail to insert into database $ENV_TEST !" 1
			log_info $info "infect line: $infect_line " 1
			return 0
		}
	} else {
		log_info $info "Already have test: $test in env: $env." 2
		return 0
	}
}

proc add_env_test_group_to_env {cur_env parent_line_group} {
        global info TEST db_handle array_test_group
        log_info $info "add env test_group to env " 2
#	incr parent_line +1
#       log_info $info "array_test(1,1): $array_test(1,1); array_test(1,2): $array_test(1,2) \n" 2
        for {set i 1} {$i <= $parent_line_group} {incr i +1} {
                if {$array_test_group($i,2)==1} {
			foreach test_to_be_add [split $array_test_group($i,3) ";"] {
				assign_test_to_env $test_to_be_add $cur_env $array_test_group($i,1)
			}
                } 
        }
}

proc add_env_test_to_env {cur_env parent_line} {
        global info TEST db_handle array_test
	#incr parent_line +1
	set group ""
        for {set i 1} {$i <= $parent_line} {incr i +1} {
                if {$array_test($i,2)==1} {
			log_info $info "handle $i: $array_test($i,1)" 2
			assign_test_to_env $array_test($i,1) $cur_env $group
                } 
        }
}

proc input_env_dev_to_db {cur_env parent_line} {
	global info ENV_DEV DB_NAME array1 group_id
#	log_info $info "parent_line: $parent_line \n" 2
#	log_info $info "array1(1,1): $array1(1,1); array1(1,2): $array1(1,2) \n" 2
	for {set i 1} {$i <= $parent_line} {incr i +1} {
		set sql_qur "INSERT INTO $ENV_DEV (`env_name`,`dev`,`group_id`) VALUES('$cur_env','$array1($i,1)','$group_id')"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set infect_line [lindex $sky_response 0]

		log_info $info $sql_qur 5
		if {$array1($i,2)==1} {
			if {$infect_line =="1"} {
				set log_content "Insert Into database $ENV_DEV successfully!\n"
				log_info $info $log_content 2
			} else {
				log_info $info "Fail to insert into database $ENV_DEV !\n" 1
				log_info $info "infect line: $infect_line \n" 1
			}
		} else {}
	}
}

proc add_env_test {add_test_to_env old_test_list} {
#invoked by edit_env_test_group
        global row1 array_test array_test_group info TEST DEV_TB DB_NAME cur_env commit TEST_GROUP
# if invoking from man_test, then add_test_to_env is 0, otherwise it is 1. 
# when invoking from man_test, old_test_list should be already set with test_list value, then in this browsing, the checkbox should be checked
	set old_test_list ";$old_test_list"

        set w_new_test .add_new_test
        catch {destroy $w_new_test}
        toplevel $w_new_test
        wm title $w_new_test "Add test item in this env"
        wm iconname $w_new_test "iconname?"
        positionWindow $w_new_test
	set parent_line_group 0
	if {$add_test_to_env==1} {
#create frame window w_test_group_frame for test group list
	        set test_group_list [ScrolledWindow $w_new_test.test_group -relief sunken -borderwidth 2 -auto horizontal]
        	set stest_group_list [ScrollableFrame $w_new_test.test_group.f -height 150  -width 400 -bg white]
	        $test_group_list setwidget $stest_group_list
        	set w_test_group_frame [$stest_group_list getframe]
	        pack $test_group_list -side top
# get test_group list from env_test_group table
	        set sql_qur "SELECT name,test_list from $TEST_GROUP where group_id='$group_id' ORDER BY name"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set parent_line_group [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

		log_info $info "$sql_qur" 5
	        if {$parent_line_group  > "0"} {
        	        log_info $info "Found $parent_line_group test_group records in DB!\n" 5
	                for {set i 1} {$i <= $parent_line_group} {incr i +1} {
				set result [lindex $sql_ret_str $k]
                                incr k +1
                	        set array_test_group($i,1) [lindex $result 0]
        	                set array_test_group($i,2) 0
                	        set array_test_group($i,3) [lindex $result 1]
                        	checkbutton $w_test_group_frame.$i -text $array_test_group($i,1) -variable array_test_group($i,2) -fg blue  -anchor w
                	        pack $w_test_group_frame.$i -side top -pady 2 -anchor w
        	        }
	        } else {
                	log_info $info "Cannot find any test group records in DB!" 2
	        }
	}
#create frame window w_test_frame for test list
        set test_list [ScrolledWindow $w_new_test.test -relief sunken -borderwidth 2 -auto horizontal]
        set stest_list [ScrollableFrame $w_new_test.test.f -height 400  -bg white -width 400]
        #set stest_list [ScrollableFrame $w_new_test.test.f -height 400 -constrainedwidth 1 -bg white -areawidth 0]
        $test_list setwidget $stest_list
        set w_test_frame [$stest_list getframe]
        pack $test_list -side top

# get test list from env_test table
        set sql_qur "SELECT test_name from $TEST where group_id='$group_id' ORDER BY test_name"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set kk 0

	log_info $info "$sql_qur" 5
        if {$parent_line >"0"} {
                log_info $info "Found $parent_line device records in DB!" 5
		set array_test(0,1) ""
		set i 1
                for {set k 1} {$k <= $parent_line} {incr k +1} {
			set result [lindex $sql_ret_str $kk]
                        incr kk +1
			set j [expr $i -1]
			if {$result!=$array_test($j,1)} {
                                set array_test($i,1) $result 
        			set test_in_list ";$array_test($i,1);"
        			if {[string first $test_in_list $old_test_list]==-1} {
        	                        set array_test($i,2) 0
        			} else {
        				set array_test($i,2) 1
        			}
                                log_info $info "cur_env:$cur_env" 6
                                log_info $info "array_test($i,1): $array_test($i,1); array_test($i,2): $array_test($i,2)" 6
        			#if {[string index $array_test($i,3) end]!=";"} {append array_test($i,3) ";"}
                                log_info $info "array_test($i,1): $array_test($i,1); array_test($i,2): $array_test($i,2)" 6
                                checkbutton $w_test_frame.$i -text $array_test($i,1) -variable array_test($i,2) -anchor w
                                pack $w_test_frame.$i -side top -pady 2 -anchor w
				incr i +1
			}
                }
        } else {
                log_info $info "Cannot find any test records in DB!\n You need add tests firstly" 2
        }
	set parent_line $j
        frame $w_new_test.command
        button $w_new_test.command.confirm -text Confirm -command " 
		if {$add_test_to_env==1} { 
			add_env_test_group_to_env $cur_env $parent_line_group ; 
			add_env_test_to_env $cur_env $parent_line ; 
		} ;
		set commit 1;"
        button $w_new_test.command.cancel -text Cancel -command " set commit 0;"
        pack $w_new_test.command -side bottom  -fill x -pady 2m
        pack $w_new_test.command.confirm $w_new_test.command.cancel -side left -expand 1
	vwait commit
	catch {destroy $w_new_test}
	return commit
}
proc add_env_subst {subst_value} {
	global info ENV_DEV DB_NAME cur_env hlp_subst_dut_cfg hlp_subst_others_cfg
	if {$subst_value=="subst_dut"} {
		set hlp_value "$hlp_subst_dut_cfg"
	} else {
		set hlp_value "$hlp_subst_others_cfg"
	}
	set sql_qur "INSERT INTO $ENV_DEV (`env_name`,`dev`,`cfg`,`group_id`) VALUES('$cur_env','$subst_value','$hlp_value','$group_id')"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]


        log_info $info $sql_qur 5
        if {$infect_line =="1"} {
        	set log_content "Insert Into database $ENV_DEV successfully!\n"
                log_info $info $log_content 2
        } else {
                log_info $info "Fail to insert into database $ENV_DEV !\n" 1
                log_info $info "infect line: $infect_line \n" 1
        }
}
proc chg_env_dev {cur_env} {
	global info
        set w .change_env_dev
        catch {destroy $w}
        toplevel $w
        wm title $w "Change device under this ENV"
        wm iconname $w "iconname?"
        positionWindow $w

        frame $w.left
        frame $w.right1
        frame $w.right2
        frame $w.command
        pack $w.left $w.right1 $w.right2 -side left -expand yes -padx 10 -pady 10 -fill both
        pack $w.command -side bottom  -fill x -pady 2m
        label $w.left.env_name -text "  " -padx 0 -width 20 -anchor e
        label $w.left.dev_name -text "Device name:" -padx 0 -width 20 -anchor e
        label $w.left.options -text "Options:" -padx 0 -width 30 -anchor e


        set entry_widget1 [entry $w.right1.env_dut -width 30 -relief sunken -textvariable env_dut]
        button $w.right1.sele -text "Original" -width 15 -command "get_device $entry_widget1; "
        set entry_widget11 [entry $w.right1.env_options -width 30 -relief sunken -textvariable env_options]


        set entry_widget2 [entry $w.right2.env_dut -width 30 -relief sunken -textvariable env_dut_new]
        button $w.right2.sele -text "Change to" -width 15 -command "get_device $entry_widget2; "
        set entry_widget22 [entry $w.right2.env_options -width 30 -relief sunken -textvariable env_options_new]

        button $w.command.confirm -text Confirm -command " 
                cfm_chg_env_dev $cur_env $entry_widget1 $entry_widget2 $entry_widget11 $entry_widget22 $w; 
		return 1 "
        button $w.command.cancel -text Cancel -command " catch {destroy $w} ; return 0 "
        pack $w.left.env_name $w.left.dev_name $w.left.options -side top -expand yes -pady 2 -anchor e
        pack $w.right1.sele $w.right1.env_dut $w.right1.env_options -side top -expand yes -pady 2 -anchor w
        pack $w.right2.sele $w.right2.env_dut $w.right2.env_options -side top -expand yes -pady 2 -anchor w
        pack $w.command.confirm $w.command.cancel -side top -expand 1
}
proc cfm_chg_env_dev {cur_env widget_from widget_to widget_from_options widget_to_options widget_win} {
	global info
	set dev_from [$widget_from get]
	set dev_to [$widget_to get]
	set options_from [string trim [$widget_from_options get]]
	set options_to [string trim [$widget_to_options get]]

        after idle {.dialog1.msg configure -wraplength 4i}
        set i [tk_dialog .dialog1 "Change device under env" " You select to change Device from $dev_from to $dev_to, that means \
        all $dev_from under $cur_env will be changed to $dev_to, Are you sure?" info 0 OK Cancel]
        switch $i {
            0 {
		if {[cfm_chg_env_dev_db $cur_env $dev_from $dev_to $options_from $options_to]==1} {
			log_info $info "Change device from $dev_from to $dev_to under env $cur_env successfully" 2
		} else {
			log_info $info "Failed to change device from $dev_from to $dev_to under env $cur_env " 2
		}
              }
            1 {log_info $info "Cancel Changing Device" 2}
        }
	catch {destroy $widget_win}
}
proc cfm_chg_env_dev_db {cur_env dev_from dev_to options_from options_to} {
	global info map1 ENV_DEV DB_NAME ENV_TEST TEST
	set dev_from [string toupper $dev_from]
	set dev_to [string toupper $dev_to]

	set options_from [handle_string_special $options_from]
	set options_to [handle_string_special $options_to]
	#####setup map. this will influnce the running mapping. 
        if {[set_map $dev_from $dev_to $options_from $options_to]!=0} {
                log_info $info "From cfm_chg_env_dev_db: Map from $dev_from to $dev_to successfully" 3
                show_map
        } else {
                log_info $info "Fail to map from $dev_from to $dev_to" 2
		return 0
        }
	#####finish setting up map

	#####Change ENV_DEV
        catch {unset chg}
        set sql_qur "SELECT id,cfg FROM $ENV_DEV WHERE ((dev='$dev_from') and (env_name='$cur_env' or env_name like '$cur_env/%') and group_id='$group_id')"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        if {$infect_line !="0"} {
                log_info $info "Change env_name in $ENV_DEV table! $infect_line" 3
                for {set i 1} {$i<=$infect_line} {incr i +1} {
                        set value_string [lindex $sql_ret_str $k]
                        incr k +1
                        set chg($i,1) [lindex $value_string 0]  
                        set chg($i,2) [handle_string_special [lindex $value_string 1]]
			set chg($i,2) [chg_string_by_map map1 $chg($i,2)]
                }
                for  {set i 1} {$i<=$infect_line} {incr i +1} {
                        set sql_qur "UPDATE $ENV_DEV set cfg='$chg($i,2)',dev='$dev_to' where id='$chg($i,1)'"
		        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line1 [lindex $sky_response 0]
 
                        if {$infect_line1 =="1"} {
                                log_info $info "Change dev_name in $ENV_DEV table successfully! $chg($i,1)" 3
                        } else {
                                log_info $info "Change env_name in $ENV_DEV table failed ! $chg($i,1)" 2
				return 0
                        }
                }
        } else {
                log_info $info "No other dev_name in $ENV_DEV table need be changed !" 2
        }
	#####Change ENV_DEV finished

        #####Change ENV_TEST and TEST
	#####Search ENV_TEST firstly and then check TEST, If TEST contain Changing device, then add one same TEST item with different name, 
	#####and then change test name in ENV_TEST table
        catch {unset chg}
        set sql_qur "SELECT id, test_name FROM $ENV_TEST WHERE ((env_name='$cur_env' or env_name like '$cur_env/%') and group_id='$group_id')"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0
 
        if {$infect_line != "0"} {
                log_info $info "Test elements under $cur_env is $infect_line!" 3
                for {set i 1} {$i<=$infect_line} {incr i +1} {
                        set value_string [lindex $sql_ret_str $k]
                        incr k +1
                        set chg($i,1) [lindex $value_string 0]
                        set chg($i,2) [lindex $value_string 1]
                }
                for  {set i 1} {$i<=$infect_line} {incr i +1} {
			set sql_qur "SELECT * FROM $TEST WHERE test_name='$chg($i,2)' and group_id='$group_id' "
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line1 [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]
                        set k 0
 
			log_info $info "sql_qur: $sql_qur. i=$i" 2
                        if {$infect_line1 >0} {
	                        set value_string [lindex $sql_ret_str $k]
                                incr k +1
				catch {unset chg_test}
        	                set chg_test($i,1) [lindex $value_string 0]
        	                set chg_test($i,2) [lindex $value_string 1]
        	                set chg_test($i,3) [lindex $value_string 2]
				#des
                	        set chg_test($i,4) [handle_string_special [lindex $value_string 3]]
        	                set chg_test($i,5) [lindex $value_string 4]
				#cmd
                	        set chg_test($i,6) [handle_string_special [lindex $value_string 5]]
				#src
                	        set chg_test($i,7) [string toupper [lindex $value_string 6]]
        	                set chg_test($i,8) [lindex $value_string 7]
        	                set chg_test($i,9) [lindex $value_string 8]
				#pre_src
                	        set chg_test($i,10) [string toupper [lindex $value_string 9]]
				#pre_cmd
                	        set chg_test($i,11) [handle_string_special [lindex $value_string 10]]
				#post_src
                	        set chg_test($i,12) [string toupper [lindex $value_string 11]]
				#post_cmd
                	        set chg_test($i,13) [handle_string_special [lindex $value_string 12]]
        	                set chg_test($i,14) [lindex $value_string 13]
        	                set chg_test($i,15) [lindex $value_string 14]
        	                set chg_test($i,16) [lindex $value_string 15]
        	                set chg_test($i,17) [lindex $value_string 16]
        	                set chg_test($i,18) [lindex $value_string 17]
        	                set chg_test($i,19) [lindex $value_string 18]
        	                set chg_test($i,20) [lindex $value_string 19]
        	                set chg_test($i,21) [lindex $value_string 20]
        	                set chg_test($i,22) [lindex $value_string 21]
        	                set chg_test($i,23) [lindex $value_string 22]

				###change description
				set chg_test($i,4) [chg_string_by_map map1 $chg_test($i,4)]
				set changed 0
				###change src&cmd
				if {$chg_test($i,7)==$dev_from} { 
					set chg_test($i,6) [chg_string_by_map map1 $chg_test($i,6)]; 
					set chg_test($i,7) $dev_to 
					set changed 1
				}
				###change pre_src&pre_cmd
				if {$chg_test($i,10)==$dev_from} { 
					set chg_test($i,11) [chg_string_by_map map1 $chg_test($i,11)];
					set chg_test($i,10) $dev_to
					set changed 1
				}
				###change post_src&post_cmd
				if {$chg_test($i,12)==$dev_from} { 
					set chg_test($i,13) [chg_string_by_map map1 $chg_test($i,13)];
					set chg_test($i,12) $dev_to
					set changed 1
				}

				####Create a new test item with same content as before except changing
				if {$changed==1} {
					set chg_test($i,2) [chg_string_by_map map1 $chg_test($i,2)];
					if {[string toupper [string range [trimfirst $chg_test($i,2)] 0 3]]!="DUT_"} {
						set chg_test($i,2) "DUT_$chg_test($i,2)"
					}
		                        set sql_qur5 "SELECT * FROM $TEST WHERE test_name='$chg_test($i,2)' and group_id='$group_id' "
                                        set sky_response5 [mysql_pack $sql_qur5 $DB_NAME ]
                                        set infect_line5 [lindex $sky_response5 0]
                                        set sql_ret_str5 [lindex $sky_response5 1]
 
		                        if {$infect_line5 >0} {
						#means there is already a test with same name
						set sql_qur6 "UPDATE $TEST set des='$chg_test($i,4)',cmd='$chg_test($i,6)',src='$chg_test($i,7)',pre_src='$chg_test($i,10)',pre_cmd='$chg_test($i,11)',post_src='$chg_test($i,12)',post_cmd='$chg_test($i,13)'  WHERE test_name='$chg_test($i,2)' and group_id='$group_id'"
					} else {
						#means there is not same name test, we have to create a new one
						set sql_qur6 "INSERT INTO $TEST values('','$chg_test($i,2)','$chg_test($i,3)','$chg_test($i,4)','$chg_test($i,5)','$chg_test($i,6)','$chg_test($i,7)','$chg_test($i,8)','$chg_test($i,9)','$chg_test($i,10)','$chg_test($i,11)','$chg_test($i,12)','$chg_test($i,13)','$chg_test($i,14)','$chg_test($i,15)','$chg_test($i,16)','$chg_test($i,17)','$chg_test($i,18)','$chg_test($i,19)','$chg_test($i,20)','$chg_test($i,21)','$chg_test($i,22)','$chg_test($i,23)','$operator','$group_id')"
					}
					log_info $info "sql_stat: $sql_qur6 " 2
                                        set sky_response6 [mysql_pack $sql_qur6 $DB_NAME ]
                                        set infect_line6 [lindex $sky_response6 0]
                                        set sql_ret_str6 [lindex $sky_response6 1]
 
                                        if {$infect_line6=="1"} {
                                                log_info $info "Insert test $chg_test($i,2) Into TEST database successfully! $infect_line3" 3
                                        } else {
                                                log_info $info "Fail to insert chg_test($i,2) into TEST database ! $infect_line3" 2
#						return 0
                                        }
                			set sql_qur4 "UPDATE $ENV_TEST set test_name='$chg_test($i,2)' where id='$chg($i,1)' and group_id='$group_id'"
                                        set sky_response4 [mysql_pack $sql_qur4 $DB_NAME ]
                                        set infect_line4 [lindex $sky_response4 0]
                                        set sql_ret_str4 [lindex $sky_response4 1]
 
                                        if {$infect_line4 =="1"} {
                                                log_info $info "Change test_name to $chg_test($i,2) in $ENV_TEST table successfully! $infect_line4" 3
                                        } else {
                                                log_info $info "Change test_name to $chg_test($i,2) in $ENV_TEST table failed ! $infect_line4" 2
						return 0
                                        }
				}
                        } else {
                                log_info $info "Can not find test name $chg($i,2)! $infect_line1" 2
                        }
                }
        } else {
                log_info $info "No other TEST in $ENV_TEST table need be changed !" 2
        }
        #####Change ENV_TEST finished
	return 1
}

proc add_env_dev {} {
	global row1 array1 info DEV_TB DB_NAME DB_PRV_NAME  cur_env user_id

	set w_dev .add_new_env
	catch {destroy $w_dev}
	toplevel $w_dev
	wm title $w_dev "Add devices in this env"
	wm iconname $w_dev "iconname?"
	positionWindow $w_dev

#create frame window man_win for device list
        set dev_list [ScrolledWindow $w_dev.dev -relief sunken -borderwidth 2]
        set sdev_list [ScrollableFrame $w_dev.dev.f -height 500 -width 220 -constrainedwidth 1 -bg white]
        $dev_list setwidget $sdev_list
        set w [$sdev_list getframe]
        pack $dev_list -side top
# get device list from dev_access table
	set sql_qur "SELECT name from $DEV_TB where user_id='$user_id' ORDER BY name "
        set sky_response [mysql_pack $sql_qur $DB_PRV_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

	if {$parent_line >"0"} {
		log_info $info "Found $parent_line device records in DB!\n" 5
		for {set i 1} {$i <= $parent_line} {incr i +1} {
			set array1($i,1) [lindex $sql_ret_str $k]
                        incr k +1
			set array1($i,2) 0 
			log_info $info "array1($i,1): $array1($i,1); array1($i,2): $array1($i,2)" 6
			checkbutton $w.$i -text $array1($i,1) -variable array1($i,2) -anchor w
			pack $w.$i -side top -pady 2 -anchor w
		}
	} else {
		log_info $info "Cannot find any device records in DB!\n You need add device firstly" 2
		return 0
	}
	frame $w_dev.command
	button $w_dev.command.confirm -text Confirm -command " input_env_dev_to_db $cur_env $parent_line ; catch {destroy $w_dev} "
	button $w_dev.command.cancel -text Cancel -command " catch {destroy $w_dev} ; return 0 " 
	pack $w_dev.command -side bottom  -fill x -pady 2m
	pack $w_dev.command.confirm $w_dev.command.cancel -side left -expand 1	
}

proc update_cfg_in_db {cfg_txt cfg_dev} {
	global info ENV_DEV cur_env array1 db_handle tag_for_prv ENV_DEV_PRV group_id
	set new_content [$cfg_txt get 1.0 end]
	#set new_content [string map {\" \\" \' \\'} $new_content]
        log_info $info "old: $new_content" 2
	set new_content [handle_string_special $new_content]
        log_info $info "new: $new_content" 2
	set reg_string "(.*)$tag_for_prv\(.*)"
	if {[regexp $reg_string $new_content no_use public_value private_value]==1} {
		append public_value $tag_for_prv
                ###update private table
		set sql_qur "SELECT id from $ENV_DEV_PRV WHERE env_name='$cur_env' and dev='$cfg_dev' and group_id='$group_id'"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set parent_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

	        log_info $info "$sql_qur" 5
	        if {$parent_line >"0"} {
			set sql_qur "UPDATE $ENV_DEV_PRV SET cfg='$private_value' WHERE env_name='$cur_env' and dev='$cfg_dev' and group_id='$group_id'"
		} else {
			set sql_qur "INSERT INTO $ENV_DEV_PRV (`env_name`,`dev`,`cfg`,`user_id`) VALUES('$cur_env','$cfg_dev','$private_value','$user_id')"
		}

                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]

                if {$infect_line =="1"} {
                	log_info $info "UPDATE value in private table successfully!" 2
	        	log_info $info "new dev_cfg: $new_content" 5
        	} else {
        	       	log_info $info "Fail to update private table $ENV_DEV_PRV !" 2
                	log_info $info "infect line: $infect_line . should be 1 " 2
                }
	} else {
		set public_value $new_content
	}
        log_info $info "public:$public_value" 2
	###update public table
	set sql_qur "UPDATE $ENV_DEV SET cfg='$public_value' WHERE env_name='$cur_env' and dev='$cfg_dev' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

	if {$infect_line =="1"} {
		log_info $info "UPDATE value successfully!" 2
		log_info $info "new dev_cfg: $new_content" 5
	} else {
		log_info $info "Fail to insert into database $ENV_DEV !\n" 1
		log_info $info "infect line: $infect_line \n . should be 1 " 1
	}
}

proc dele_dev_env {cur_widget} {
        global info array1 cur_env ENV_DEV db_handle group_id
        log_info $info "cur_widget: $cur_widget;" 6
        regexp \.f\.out_window\.oper\.dev_sw\.f\.frame\.(\[0-9]*) $cur_widget unuse no
        log_info $info "array1($no,1): $array1($no,1);" 6

        after idle {.dialog1.msg configure -wraplength 4i}
        set i [tk_dialog .dialog1 "Confirm " " delete $array1($no,1) from $cur_env. \r Are you sure?" info 0 OK Cancel]
        switch $i {
            0 {
                log_info $info "Start to delete $array1($no,1) from $cur_env" 5
                set sql_qur "SELECT id from $ENV_DEV where env_name='$cur_env' and dev='$array1($no,1)' and group_id='$group_id'"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set parent_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

                log_info $info "$sql_qur" 6
                if {$parent_line >"0"} {
                        log_info $info "Found $parent_line same dev records in DB . dev_name:$array1($no,1))" 2
                        set del_id [lindex $sql_ret_str $k]
                        set sql_qur "DELETE from  $ENV_DEV where id='$del_id' and group_id='$group_id'"
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line [lindex $sky_response 0]
                        set sql_ret_str [lindex $sky_response 1]


                        if {$infect_line == "1"} {
                                log_info $info "Delete first test $array1($no,1) from env: $cur_env successfully!" 3
                                return 1
                        } else {
                                log_info $info "Fail to delete test $array1($no,1) from env: $cur_env from database !" 2
                                return 0
                        }
                } else {
                        log_info $info "Cannot find device $array1($no,1) for $cur_env to delete. parent_line: $parent_line" 2
                        return 0
                }
              }
            1 {log_info $info "Cancel deletion!" 2}
        }
}

proc del_test {num} {
#invoked by man_test
        global info row1 array2 DB_NAME TEST group_id
        set sql_qur "DELETE FROM $TEST WHERE test_name='$array2($num,2)' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
        if {$infect_line == "1"} {
                log_info $info "Successful to delete test $array2($num,2) in table $TEST!" 3
                return 1
        } else {
                log_info $info "Fail to delete $array2($num,2) from table $TEST !" 2
                log_info $info "$infect_line" 3
                return 0
        }
}
proc dele_test_env {cur_widget} {
#invoked by list_test_for_env 
        global info array1 cur_env ENV_TEST DB_NAME array_test
        log_info $info "cur_widget: $cur_widget;" 6
        regexp \.f\.out_window\.oper\.test_sw\.f\.frame\.(\[0-9]*) $cur_widget unuse no
        log_info $info "array_test($no,1): $array_test($no,1);" 6

        set i [tk_dialog .dialog1 "Confirm to delete test $array_test($no,1)" " You selected to delete test $array_test($no,1) from $cur_env,Are you sure?" info 0 OK Cancel]
        switch $i {
            0 {
                log_info $info "deleting test $array_test($no,1) from $cur_env " 2
		dele_test_env_exec $cur_widget
              }
            1 {log_info $info "Cancel deleting" 2}
        }
}
proc dele_test_env_exec {cur_widget} {
        global info array1 cur_env ENV_TEST db_handle array_test group_id
        log_info $info "cur_widget: $cur_widget;" 6
        regexp \.f\.out_window\.oper\.test_sw\.f\.frame\.(\[0-9]*) $cur_widget unuse no
        log_info $info "array_test($no,1): $array_test($no,1);" 6

# get env_name list in TEST table 
	set sql_qur "SELECT id from $ENV_TEST where test_name='$array_test($no,1)' and env_name='$cur_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
        if {$parent_line >"0"} {
                log_info $info "Found $parent_line same test records in DB . test_name:$array_test($no,1))" 2
		set del_id [lindex $sql_ret_str $k] 
		set sql_qur "DELETE from  $ENV_TEST where id='$del_id' and group_id='$group_id'"
                set sky_response [mysql_pack $sql_qur $DB_NAME ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

	        if {$infect_line =="1"} {
        	        log_info $info "Delete first test $array_test($no,1) from env: $cur_env successfully!" 3
			return 1
	        } else {
        	        log_info $info "Fail to delete test $array_test($no,1) from env: $cur_env from database !" 2
			return 0
        	}
        } else {
                log_info $info "Cannot find test item : $array_test($no,1) for env:$cur_env" 2
		return 0
        }
}


proc confirm_chg_test_exp_result {no } {
	global DB_NAME ENV_TEST array_test info pre_result result post_result group_id
		set array_test($no,5) [setbitvalue $array_test($no,5) 2 $pre_result];
		set array_test($no,5) [setbitvalue $array_test($no,5) 1 $result];
		set array_test($no,5) [setbitvalue $array_test($no,5) 0 $post_result];
	log_info $info "no:$no, pre:$pre_result, mid:$result, post:$post_result, array:$array_test($no,5)" 2

	set sql_qur "UPDATE $ENV_TEST set exp_result='$array_test($no,5)' where test_name='$array_test($no,1)' and env_name='$array_test($no,3)' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0



        log_info $info "$sql_qur" 6
        if {$parent_line > "0"} {
                log_info $info "successful to change expect behavior !" 2
		set ::commit_chg_test_exp_result 1
                return 1
        } else {
                log_info $info "failed to change expect behavior!" 2
		set ::commit_chg_test_exp_result 0
                return 0
        }
}

proc change_expect {cur_widget} {
#invoked by list_test_for_env
        global info array1 cur_env ENV_TEST db_handle array_test group_id
        log_info $info "cur_widget: $cur_widget;" 6
	if {[$cur_widget cget -foreground]=="red"} {
		set cur_value 1
		set new_value 0
		$cur_widget configure -foreground black
	} else {
		set cur_value 0
		set new_value 1
		$cur_widget configure -foreground red
	}
        regexp \.f\.out_window\.oper\.test_sw\.f\.frame\.(\[0-9]*) $cur_widget unuse no
        log_info $info "array_test($no,1): $array_test($no,1);" 6
        set sql_qur "UPDATE $ENV_TEST set exp_result='$new_value' where test_name='$array_test($no,1)' and env_name='$cur_env' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
        if {$parent_line > "0"} {
                log_info $info "successful to change expect behavior for $cur_env from $cur_value to $new_value!" 2
                return 1
        } else {
                log_info $info "failed to change expect behavior for $cur_env from $cur_value to $new_value!" 2
                return 0
        }
}


proc upgrade_img {device version build platform outdeb} {
	global info TFTPSVR interrupt FG_IMAGE_USER FG_IMAGE_PASS FG_IMAGE_SVR TFTPDIR
	set interrupt 0
	log_info $info "device: $device; version: $version; build: $build; platform: $platform $outdeb version" 2
#	getimage v$version build$build $platform $outdeb
        set fg_image_dir "$TFTPDIR/fg_image"
        set filename FGT_$platform-v$version-build$build-FORTINET.$outdeb
        if { ![file exist $fg_image_dir/$filename] } {
        	#put image to TFTP server
                set cmd_svr "
                mkdir $fg_image_dir
        	ncftpget -u $FG_IMAGE_USER -p $FG_IMAGE_PASS -F $FG_IMAGE_SVR $fg_image_dir FortiOS/v$version/build$build/$filename"
                run_comm_on_dev $TFTPSVR $cmd_svr 1
	}
	#upgrade image from TFTP server
	set cmd "config global
		exec restore image fg_image/$filename $TFTPSVR
		exec restore image tftp fg_image/$filename $TFTPSVR"
        run_comm_on_dev $device $cmd 1
	return 1
}
proc chg_env_test_order {widget} {
#Invoked by list_test_by_env
        global info array_test cur_env ENV_DEV db_handle commit_chg_env_test_order
#get the number of the running_widget
        regexp \.f\.out_window\.oper\.test_sw\.f\.frame\.(\[0-9]*) $widget unuse no
	set test_name $array_test($no,1)
	set env_name $array_test($no,3)
	set order_value $array_test($no,11)
        set w .chg_env_test_order
        catch {destroy $w}
        toplevel $w
        wm title $w "Change order for the Test"
        wm iconname $w "iconname?"
        positionWindow $w
        frame $w.left
        frame $w.right
        frame $w.command
        pack $w.left $w.right -side left -expand yes -padx 10 -pady 10 -fill both
        pack $w.command -side bottom  -fill x -pady 2m

        label $w.left.test_name -text "Test name" -padx 0 -width 15 -anchor e

        label $w.left.env_name -text "Current env" -padx 0 -width 15 -anchor e
        label $w.left.old_order -text "Old order value" -padx 0 -width 15 -anchor e
        label $w.left.new_order -text "New order value" -padx 0 -width 15 -anchor e
	log_info $info "test_name: $test_name, env_name:$env_name, order:$order_value" 2
	
	label $w.right.test_name -text "$test_name" -relief sunken -width 40 -anchor e
	label $w.right.env_name -text "$env_name" -relief sunken -width 40 -anchor e
	label $w.right.old_order -text "$order_value" -relief sunken -width 5 -anchor e
        entry $w.right.new_order -width 5 -relief sunken 

        button $w.command.confirm -text Confirm -command "[list confirm_chg_env_test_order $test_name $env_name $order_value $w.right.new_order $w]; set commit_chg_env_test_order 1"
        button $w.command.cancel -text Cancel -command [list set commit_chg_env_test_order 0]
        pack $w.command.confirm $w.command.cancel -side top -expand 1
        pack $w.left.test_name $w.left.env_name $w.left.old_order $w.left.new_order -side top -expand yes -pady 2 -anchor w
        pack $w.right.test_name $w.right.env_name $w.right.old_order $w.right.new_order -side top -expand yes -pady 2 -anchor w
        vwait commit_chg_env_test_order;
	catch {destroy $w}
        return $commit_chg_env_test_order
}

proc chg_env_dev_order {widget} {
#Invoked by list_dev_by_env
        global info array1 cur_env ENV_DEV db_handle commit_chg_env_dev_order
#get the number of the running_widget
        regexp \.f\.out_window\.oper\.dev_sw\.f\.frame\.(\[0-9]*) $widget unuse no
	set dev_name $array1($no,1)
	set env_name $array1($no,3)
	set order_value $array1($no,4)
        set w .chg_env_dev_order
        catch {destroy $w}
        toplevel $w
        wm title $w "Change order for the device"
        wm iconname $w "iconname?"
        positionWindow $w
        frame $w.left
        frame $w.right
        frame $w.command
        pack $w.left $w.right -side left -expand yes -padx 10 -pady 10 -fill both
        pack $w.command -side bottom  -fill x -pady 2m

        label $w.left.dev_name -text "Device name" -padx 0 -width 15 -anchor e

        label $w.left.env_name -text "Current env" -padx 0 -width 15 -anchor e
        label $w.left.old_order -text "Old order value" -padx 0 -width 15 -anchor e
        label $w.left.new_order -text "New order value" -padx 0 -width 15 -anchor e
	log_info $info "dev_name: $dev_name, env_name:$env_name, order:$order_value" 2
	
	label $w.right.dev_name -text "$dev_name" -relief sunken -width 40 -anchor e
	label $w.right.env_name -text "$env_name" -relief sunken -width 40 -anchor e
	label $w.right.old_order -text "$order_value" -relief sunken -width 5 -anchor e
        entry $w.right.new_order -width 5 -relief sunken 

        button $w.command.confirm -text Confirm -command "[list confirm_chg_env_dev_order $dev_name $env_name $order_value $w.right.new_order $w]; set commit_chg_env_dev_order 1"
        button $w.command.cancel -text Cancel -command [list set commit_chg_env_dev_order 0]
        pack $w.command.confirm $w.command.cancel -side top -expand 1
        pack $w.left.dev_name $w.left.env_name $w.left.old_order $w.left.new_order -side top -expand yes -pady 2 -anchor w
        pack $w.right.dev_name $w.right.env_name $w.right.old_order $w.right.new_order -side top -expand yes -pady 2 -anchor w
        vwait commit_chg_env_dev_order;
	catch {destroy $w}
        return $commit_chg_env_dev_order
}
proc chg_img_from_list {widget} {
        global info array1 cur_env ENV_DEV db_handle platform_list version_list deb_out_list commit_chg_img
#get the number of the running_widget
        regexp \.f\.out_window\.oper\.dev_sw\.f\.frame\.(\[0-9]*) $widget unuse no
	set dev_name $array1($no,1)
        set w .chg_img
        catch {destroy $w}
        toplevel $w
        wm title $w "Change image for the device"
        wm iconname $w "iconname?"
        positionWindow $w
        frame $w.left
        frame $w.right
        frame $w.command
        pack $w.left $w.right -side left -expand yes -padx 10 -pady 10 -fill both
        pack $w.command -side bottom  -fill x -pady 2m

        label $w.left.dev_name -text "Device name" -padx 0 -width 15 -anchor e

        label $w.left.dev_platform -text "Platform" -padx 0 -width 15 -anchor e
        label $w.left.dev_version -text "Version" -padx 0 -width 15 -anchor e
        label $w.left.dev_build -text "Build" -padx 0 -width 15 -anchor e
        label $w.left.dev_outdeb -text "Out/Deb" -padx 0 -width 15 -anchor e
	
	label $w.right.dev_name -text "$dev_name" -relief sunken -width 15 -anchor e
	set platform ""
        ComboBox $w.right.dev_platform -values $platform_list -text "$platform" -helptext "select platform mode" 
	set version "300"
        ComboBox $w.right.dev_version -values $version_list -text "$version" -helptext "select version" 
	set build ""
        entry $w.right.dev_build -width 20 -relief sunken 
	set special "out"
        ComboBox $w.right.dev_outdeb -values $deb_out_list -text "$special" -helptext "select debug or output build" 

        button $w.command.confirm -text Confirm -command "[list confirm_chg $dev_name $w.right.dev_platform $w.right.dev_version $w.right.dev_build $w.right.dev_outdeb $w ]; set commit_chg_img 1"
        button $w.command.cancel -text Cancel -command [list set commit_chg_img 0]
        pack $w.command.confirm $w.command.cancel -side left -expand 1
        pack $w.left.dev_name $w.left.dev_platform $w.left.dev_version $w.left.dev_build $w.left.dev_outdeb -side top -expand yes -pady 2 -anchor w
        pack $w.right.dev_name $w.right.dev_platform $w.right.dev_version $w.right.dev_build $w.right.dev_outdeb -side top -expand yes -pady 2 -anchor w
        vwait commit_chg_img;
	catch {destroy $w}
        return $commit_chg_img
}

proc confirm_chg_env_dev_order {dev_name env_name old_order order_widget win} {
#invoked by chg_env_dev_order	
	global info DB_NAME ENV_DEV group_id 
	set new_order_value [$order_widget get]
        set sql_qur "UPDATE $ENV_DEV SET `order`=$new_order_value WHERE env_name='$env_name' and dev='$dev_name' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]

        log_info $info $sql_qur 2
        if {$infect_line == "1"} {
                log_info $info "Update order value for $dev_name from $old_order to $new_order_value successfully!" 3
                return $new_order_value
        } else {
                log_info $info "Fail to update order value for $dev_name from $old_order to $new_order_value  !" 2
                return 0
        }
}
proc confirm_chg_env_test_order {test_name env_name old_order order_widget win} {
#invoked by chg_env_test_order	
	global info DB_NAME ENV_TEST group_id
	set new_order_value [$order_widget get]
        set sql_qur "UPDATE $ENV_TEST SET `order`=$new_order_value WHERE env_name='$env_name' and test_name='$test_name' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set infect_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info $sql_qur 2
        if {$infect_line == "1"} {
                log_info $info "Update order value for $test_name from $old_order to $new_order_value successfully!" 3
                return $new_order_value
        } else {
                log_info $info "Fail to update order value for $test_name from $old_order to $new_order_value  !" 2
                return 0
        }
}

proc confirm_chg {name platform_widget version_widget build_widget outdeb_widget win} {
	global info
	set version [$version_widget get]
	set build [$build_widget get]
	set platform [$platform_widget get]
	set outdeb [$outdeb_widget get]
	catch {destroy $win}

	log_info $info "device: $name; version: $version; build: $build; platform: $platform; $outdeb version" 2
	upgrade_img $name $version $build $platform $outdeb;
	return commit_chg_img
}
proc backup_cfg_in_tftp {env device} {
	global info operator_ip map_other map1 change_dut1 TFTPDIR TFTPSVR
	set cfgdir "$TFTPDIR/cfg"
        set cmd_svr "
	mkdir -p $cfgdir/$env
	chmod 777 $cfgdir/$env"
        run_comm_on_dev $TFTPSVR $cmd_svr 1

        
        set cmd "
end
config global
exec backup config tftp cfg/$env/cfg$device $TFTPSVR ||||||120
exec backup config cfg/$env/cfg$device $TFTPSVR ||||||120
"
                        #check if we need to change DUT
                        set device [string tolower [string trim $device]]
                        if {$device == $map1(1,1) && $change_dut1==1} {
                                set host $map1(1,2)
                                set cmd [chg_string_by_map map1 $cmd]
                        } else {
                                set host $device
                        }
                        #check if we need to change Test_support devices
                        set ii 1
                        while {[info exists map_other($ii,1,1)] && $change_dut1==1} {
log_info $info "device: $device; map_other($ii,1,1): $map_other($ii,1,1)  -> $map_other($ii,1,2)" 2
                                if {[string trim $device] == [string trim $map_other($ii,1,1)]} {
                                        set host $map_other($ii,1,2)
                                        set cmd [chg_string_by_map_other $ii map_other $cmd]
log_info $info "change config for $device" 2
                                }
                                incr ii +1
                        }

        run_comm_on_dev $host $cmd 1
        return 1
	
}
proc restore_cfg_from_tftp {env widget} {
}

proc get_cfg_of_dev_in_env {env dev} {
	global info ENV_DEV ENV_DEV_PRV db_handle tag_for_prv DB_NAME group_id
	# get cfg from ENV_DEV table
        set sql_qur "SELECT cfg from $ENV_DEV where env_name='$env' and dev='$dev' and group_id='$group_id'"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

        log_info $info "$sql_qur" 6
        if {$parent_line >"0"} {
                log_info $info "Found $parent_line device records in DB!" 4
                set dev_cfg [string range [lindex $sql_ret_str 0] 1 end-1]
                #set dev_cfg [string range [::mysql::fetch $db_handle] 1 end-1]
                log_info $info "dev_cfg in database is $dev_cfg " 2
		set last_line [string trim [lindex [split $dev_cfg "\n"] end]]	
		###Check if it need read cfg from private space
		if {$last_line==$tag_for_prv} {
		        set sql_qur "SELECT cfg from $ENV_DEV_PRV where env_name='$env' and dev='$dev' and group_id='$group_id'"
                        set sky_response [mysql_pack $sql_qur $DB_NAME ]
                        set infect_line [lindex $sky_response 0]
                        set sql_ret_str_prv [lindex $sky_response 1]
                        set k 0

		        log_info $info "$sql_qur" 6
		        if {$infect_line > "0"} {
                		log_info $info "Found $infect_line device records in private DB!" 4
				set dev_cfg_prv [string range [lindex $sql_ret_str_prv 0] 1 end-1]
			} else {
	        	        log_info $info "Cannot find pre-defined cfg for $dev in private DB!" 3
		                set dev_cfg_prv ""
		        }
			append dev_cfg $dev_cfg_prv
		}
        } else {
                log_info $info "Cannot find pre-defined cfg for this device!\n Config it as new" 3
                set dev_cfg ""
        }
	return $dev_cfg
}
proc add_command_for_dev {a can_change} {
	global info array1 cur_env ENV_DEV db_handle
	log_info $info "can_change: $can_change" 5
	log_info $info "a: $a;" 6
#	regexp \.f\.out_window\.dev_list\.(\[0-9]*) $a unuse no
	regexp \.f\.out_window\.oper\.dev_sw\.f\.frame\.(\[0-9]*) $a unuse no
	log_info $info "array1($no,1): $array1($no,1);" 6
	log_info $info "array1($no,2): $array1($no,2);" 6
	log_info $info "cur_env: $cur_env;" 6
	set w .add_command_for_dev
	catch {destroy $w}
	toplevel $w
	wm title $w "Add pre-defined commands for the device in this test"
	wm iconname $w "iconname?"
	positionWindow $w
	set dev_cfg [get_cfg_of_dev_in_env $cur_env $array1($no,1)]
	log_info $info "old dev_cfg: $dev_cfg" 5
	label $w.label -text "operating device: $array1($no,1) in env: $cur_env"
	pack $w.label -side top
	set cfg_txt [text $w.txt -yscrollcommand "$w.sb set"]
#	tk_textPaste $cfg_txt
	scrollbar $w.sb -orient vertical -command "$cfg_txt yview"
	pack $cfg_txt -side left -expand 1 -fill both
	pack $w.sb -side left -fill y
	$cfg_txt insert end $dev_cfg
	frame $w.command
	button $w.command.confirm -text "Confirm" -width 15 -command "update_cfg_in_db $cfg_txt $array1($no,1); catch {destroy $w} "
	button $w.command.backup -text "Backup Config" -width 15  -command "backup_cfg_in_tftp $cur_env $array1($no,1)"
	button $w.command.restore -text "Restore Config" -width 15 -command "restore_cfg_from_tftp $cur_env $array1($no,1) "
	button $w.command.cancel -text "Cancel" -width 15 -command " catch {destroy $w} ; return 0 " 
	pack $w.command -side right  -fill x -pady 2m
	pack $w.command.backup $w.command.restore $w.command.confirm $w.command.cancel -side top -expand 1	
}

proc check_uncheck_conf {cmd_win} {
	global info dev_no array1 
	set old_string [$cmd_win.check_conf cget -text]
	set match [string first "Uncheck" $old_string]
	if {$match >= 0} {
		set check_value 0 
		$cmd_win.check_conf configure -text "Check All Device"
	} else {
		set check_value 1
		$cmd_win.check_conf configure -text "Uncheck All Device"
	}

	for {set i 1} {$i<=$dev_no} {incr i +1} {
		set array1($i,2) $check_value
	}
}
proc check_uncheck_test {cmd_win} {
        global test_no array_test
        set old_string [$cmd_win.check_test cget -text]
        set match [string first "Uncheck" $old_string]
        if {$match >= 0} {
                set check_value 0
                $cmd_win.check_test configure -text "Check All Test"
        } else {
                set check_value 1
                $cmd_win.check_test configure -text "Uncheck All Test"
        }

        for {set i 1} {$i<=$test_no} {incr i +1} {
                set array_test($i,2) $check_value
        }
}

proc list_dev_for_envhandling {env_handling cur_win} {
	global ENV_DEV db_handle info dev_no array1 DB_NAME group_id
	log_info $info "now I'm handling env: $env_handling; dev_no is : $dev_no" 5

        set sql_qur "SELECT `dev`,`order` from $ENV_DEV where env_name='$env_handling' and group_id='$group_id' order by `order`,dev"
        set sky_response [mysql_pack "$sql_qur" $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

	# get device list associated with cur_env from dev_env table
		if {$parent_line > "0"} {
			log_info $info "Found $parent_line device records in DB!" 4
			for {set i [expr $dev_no+1]} {$i <= [expr $parent_line+$dev_no]} {incr i +1} {
				#set result [::mysql::fetch $db_handle]
                                set result [lindex $sql_ret_str $k]
                                incr k +1
				set array1($i,1) [lindex $result 0]
				set array1($i,2) 1
			        set array1($i,3) $env_handling	
				set array1($i,4) [lindex $result 1]
				log_info $info "dev_no: $dev_no; parent_line: $parent_line; array1($i,1): $array1($i,1); \
				array1($i,2): $array1($i,2); array1($i,3): $array1($i,3)" 4
#				checkbutton $cur_win.$i -variable array1($i,2) -text "$array1($i,1)  belong to env:$env_handling"  -anchor w
				frame $cur_win.$i
				checkbutton $cur_win.$i.1 -variable array1($i,2) -text "$array1($i,1)  "  -anchor w
				entry $cur_win.$i.2 -width 2 -state disable -relief sunken -textvariable array1($i,4)
				pack $cur_win.$i -side top -pady 2 -anchor w
				pack $cur_win.$i.2 $cur_win.$i.1 -side left -pady 2 -anchor w
			}
			set dev_no [expr $dev_no+$parent_line]
			log_info $info "dev_no: $dev_no" 6
		
		} else {
			set log_content "Cannot find any device records for $env_handling in DB!"
			log_info $info $log_content 3
			return 0
		}
}
proc change_test {} {
	global TEST ENV_TEST info db_handle group_id
	set sql_qur "SELECT test_name,env_name where group_id='$group_id' from $TEST"
        set sky_response [mysql_pack "$sql_qur" $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]
        set k 0

	set iii 1
        for {set ii 1} {$ii <= $parent_line} {incr ii +1}                { 
#        for {set ii 1} {$ii <= 10} {incr ii +1} 
               set result [lindex $sql_ret_str $k]
               #set result [::mysql::fetch $db_handle]
               set test [lindex $result 0]
               set cur_env_name [lindex $result 1]
               set i 1
               set aaa(1) "0"
               set name "none"
               set expect "none"
	       foreach value [split $cur_env_name ";"] {
			if {[set value [string trim $value]]!=""} {
				set aaa($i) $value
				log_info $info "aaa($i): $aaa($i)" 1
				incr i +1
			}
		}
		set aaa($i) "0"
		for {set j 1} {$j<$i} {incr j +1} {
			if {$aaa($j)!="0" && $aaa($j)!="1"} {
				set k [expr $j+1]
				if {$aaa($k)=="1" || $aaa($k)=="0"} {
					set name $aaa($j)
					set expect $aaa($k)
					incr j +1
				} else {
					set name $aaa($j)
					set expect "0"
				}
			}
			set test2($iii,1) "$name"
			set test2($iii,2) "$test"
			set test2($iii,3) "$expect"
			log_info $info " test2($iii,1): $test2($iii,1) | test2($iii,2):$test2($iii,2) | test2($iii,3): $test2($iii,3)" 2
			incr iii +1
		}
	}
	for {set ab 1} {$ab <$iii} {incr ab +1} {
        	set sql_qur "INSERT INTO env_test2 (id,env_name,test_name,test_group,exp_result,description,state,order,group_id) values('','$test2($ab,1)','$test2($ab,2)','','$test2($ab,3)','','1','$group_id')"
                set sky_response [mysql_pack "$sql_qur" $DB_NAME ]
                set infect_line [lindex $sky_response 0]
                set sql_ret_str [lindex $sky_response 1]
                set k 0

                if {[$infect_line == "1"} {
                        log_info $info "Insert $name Into env database successfully!" 3
                } else {
                        log_info $info "Fail to insert $row1(1) into env database !" 2
                }
	}
}
proc list_test_for_envhandling {env_handling cur_win} {
	global ENV_DEV db_handle info test_no array_test TEST ENV_TEST DB_NAME group_id
	log_info $info "now I'm handling test: $env_handling; test_no is : $test_no" 5
	set sql_qur "SELECT `test_name`,`exp_result`,`state`,`order` from $ENV_TEST where env_name ='$env_handling' and group_id='$group_id' order by `order`,test_name"
        set sky_response [mysql_pack $sql_qur $DB_NAME ]
        set parent_line [lindex $sky_response 0]
        set sql_ret_str [lindex $sky_response 1]

        set k 0

# get test list associated with cur_env from env_test2 table
        if {$parent_line > "0"} {
            log_info $info "Found $parent_line test items for $env_handling in DB!" 4
            for {set i [expr $test_no+1]} {$i <= [expr $parent_line+$test_no]} {incr i +1} {
                set result [lindex $sql_ret_str $k]
                incr k +1
                set array_test($i,1) [lindex $result 0]
                #value of state field in env_test table was set to array_test($i,2), works as default value to control run or not run this test
                set array_test($i,2) [lindex $result 2]
                set array_test($i,3) $env_handling	
                set array_test($i,4) 0	
	        set array_test($i,5) [lindex $result 1]	
		set bit_exp_result [int2bits $array_test($i,5)]
	        set array_test($i,11) [lindex $result 3]	
		frame $cur_win.$i
		if {$array_test($i,5)!=0} {
			checkbutton $cur_win.$i.1 -foreground red -onvalue $array_test($i,2) -variable array_test($i,2) -text "$array_test($i,1)"  -anchor w
		} else {
			checkbutton $cur_win.$i.1 -foreground black -onvalue $array_test($i,2) -variable array_test($i,2) -text "$array_test($i,1)"  -anchor w
		}
		entry $cur_win.$i.2 -width 2 -state disable -relief sunken -textvariable array_test($i,11)
		log_info $info "array_test($i,5): $array_test($i,5)" 5
		pack $cur_win.$i -side top -pady 2 -anchor w
		pack $cur_win.$i.2 $cur_win.$i.1 -side left -pady 2 -anchor w
	}
	set test_no [expr $test_no+$parent_line]
	log_info $info "test_no: $test_no" 6
} else {
	set log_content "Cannot find any test items for $env_handling in DB!"
	log_info $info $log_content 3
	return 0
}
}

proc list_dev_for_env {cur_win cur_env} {
	global ENV_DEV db_handle info dev_no popup2 array1 operator
	#set can_change [can_i_change $operator $cur_env]
	set can_change "active"
	log_info $info "can_change:$can_change; operator:$operator; cur_env:$cur_env" 6
	set cur_env1 $cur_env
	set env_handling ""
# reset widget and variable
	catch {unset array1}
	for {set i 1} {$i<=$dev_no} {incr i +1} {
		destroy $cur_win.$i
		log_info $info "destroy $cur_win.$i " 6
	}
	set dev_no "0"
	# Create a popup menu for input and check configuration for each device in different env
	catch [destroy $cur_win.popupMenu]
	if {[info exists popup2]} {catch [destroy $popup2]}
	set popup2 [menu $cur_win.popupMenu]
	set cur_widget ""
	$popup2 add command -label "Edit commands for this box" -command { add_command_for_dev $cur_widget $can_change }
	$popup2 add command -label "Delete this box from current env" -state $can_change -command {dele_dev_env $cur_widget }
	$popup2 add command -label "Change image for this box" -command {chg_img_from_list $cur_widget }
	$popup2 add command -label "Change order value" -state $can_change -command {chg_env_dev_order $cur_widget}

	log_info $info "enter list_dev_for_env, cur_env: $cur_env1, cur_win: $cur_win \n" 6
#below lines can be used to list all test device, include that belong to parent env
#	while {[set reg_value [string first / $cur_env1]]!=-1} {
#		append env_handling [string range $cur_env1 0 [expr $reg_value-1]]
#		list_dev_for_envhandling $env_handling $cur_win
#		log_info $info "Now dev_no is : $dev_no" 6
#		set cur_env1 [string range $cur_env1 [expr $reg_value+1] end]
#		append env_handling "/"
#	}
#	append env_handling $cur_env1
#	list_dev_for_envhandling $env_handling $cur_win
	list_dev_for_envhandling $cur_env $cur_win	
	for {set i 1} {$i<=$dev_no} {incr i +1} {
		bind $cur_win.$i.1 <3> {
			set cur_widget %W
			set can_change [can_i_change $operator $cur_env]
			tk_popup $popup2 %X %Y
		}
	}
}

proc list_test_for_env {cur_win cur_env} {
	global ENV_DEV db_handle info test_no popup3 array_test operator
	#set can_change [can_i_change $operator $cur_env]
	set can_change "active"
	set cur_env1 $cur_env
	set env_handling ""
# reset widget and variable
	catch {unset array_test}
	for {set i 1} {$i<=$test_no} {incr i +1} {
		destroy $cur_win.$i
		log_info $info "destroy $cur_win.$i " 6
	}
	set test_no "0"
	# Create a popup menu for input and check configuration for each device in different env
	catch [destroy $cur_win.popupMenu]
	set popup3 [menu $cur_win.popupMenu]
	$popup3 add command -label "Edit this test" -command {modi_test $cur_widget}
	$popup3 add command -label "Delete this test from current env" -state $can_change -command {dele_test_env $cur_widget }
	$popup3 add command -label "Change expect result(success/failure)" -state $can_change -command {change_expect $cur_widget}
	$popup3 add command -label "Show/modify attributes of the test in current env" -command {edit_test_env $cur_widget $can_change}
	$popup3 add command -label "change order value" -state $can_change -command {chg_env_test_order $cur_widget}

	log_info $info "enter list_test_for_env, cur_env: $cur_env1, cur_win: $cur_win \n" 6
# comment out below lines is for diabling display for parent env's test
#	while {[set reg_value [string first / $cur_env1]]!=-1} {
#		append env_handling [string range $cur_env1 0 [expr $reg_value-1]]
#		list_test_for_envhandling $env_handling $cur_win
#		log_info $info "Now test_no is : $test_no" 6
#		set cur_env1 [string range $cur_env1 [expr $reg_value+1] end]
#		append env_handling "/"
#	}
	append env_handling $cur_env1
	list_test_for_envhandling $env_handling $cur_win
	
	for {set i 1} {$i<=$test_no} {incr i +1} {
		bind $cur_win.$i.1 <3> {
		set cur_widget %W
		tk_popup $popup3 %X %Y}
	}
}

proc about_box {} {
	tk_messageBox -icon info -type ok -title "About Autotestnet" -message \
"Autotestnet

Seeking for a really useful tool for configuration and autotest? Now you find right place. 

Copyright (c) 2005- ?  Hans Yin 

Contact: hansyin@gmail.com
         hans_yin_vancouver (skype_id)
"
}	

